d = {'some_col' : ['A', 'B', 'C', 'D', 'E'],
'alert_status' : [1, 2, 0, 0, 5]}
df = pd.DataFrame(d)
我工作中的很多任务需要在熊猫中完成相同的任务.我开始编写标准化函数,将数据帧作为参数并返回一些东西.这是一个简单的:
def alert_read_text(df, alert_status=None):
if (alert_status is None):
print 'Warning: A column name with the alerts must be specified'
alert_read_criteria = df[alert_status] >= 1
df[alert_status].loc[alert_read_criteria] = 1
alert_status_dict = {0 : 'Not Read',
1 : 'Read'}
df[alert_status] = df[alert_status].map(alert_status_dict)
return df[alert_status]
df['alert_status_text'] = alert_read_text(df, alert_status='alert_status')
但是,目前,此函数将正确返回一个系列,但也会修改现有列.如何使传入的原始列不被修改?
解决方法:
正如您所发现的,传入的数据帧将被修改为params通过引用传递,这在python中是正确的,与pandas无关.
因此,如果您不想修改传递的df,那么请复制一份:
def alert_read_text(df, alert_status=None):
if (alert_status is None):
print 'Warning: A column name with the alerts must be specified'
copy = df.copy()
alert_read_criteria = copy[alert_status] >= 1
copy[alert_status].loc[alert_read_criteria] = 1
alert_status_dict = {0 : 'Not Read',
1 : 'Read'}
copy[alert_status] = copy[alert_status].map(alert_status_dict)
return copy[alert_status]