我有一个pandas数据框,我需要添加一个新列,它将基于特定列的计算,由列“站点”指示。我找到了一种方法,通过numpy来做到这一点,但它总是给出关于链式索引的警告。我相信应该有更好的解决方案,如果你知道的话请帮忙。
df_num_bin1['Chip_id_3']=np.where(df_num_bin1[key_site_num]==1,df_num_bin1[WB_89_S1]*0x100+df_num_bin1[WB_78_S1],df_num_bin1[WB_89_S2]*0x100+df_num_bin1[WB_78_S2])
df_num_bin1['Chip_id_2']=np.where(df_num_bin1[key_site_num]==1,df_num_bin1[WB_67_S1]*0x100+df_num_bin1[WB_56_S1],df_num_bin1[WB_67_S2]*0x100+df_num_bin1[WB_56_S2])
df_num_bin1['Chip_id_1']=np.where(df_num_bin1[key_site_num]==1,df_num_bin1[WB_45_S1]*0x100+df_num_bin1[WB_34_S1],df_num_bin1[WB_45_S2]*0x100+df_num_bin1[WB_34_S2])
df_num_bin1['Chip_id_0']=np.where(df_num_bin1[key_site_num]==1,df_num_bin1[WB_23_S1]*0x100+df_num_bin1[WB_12_S1],df_num_bin1[WB_23_S2]*0x100+df_num_bin1[WB_12_S2])
df_num_bin1['mac_low']=(df_num_bin1['Chip_id_1'].map(int) % 0x10000) *0x100+df_num_bin1['Chip_id_0'].map(int) // 0x1000000
上面的代码有两个问题:
1:这里列[key_site_num]的值决定了我应该从哪些列中提取芯片id数据。在这个例子中,它只是站点0或1,但实际上也可能是2或3。我需要一个通用的解决方案。
2:它生成链式索引警告;
C:\Anaconda2\lib\site-packages\ipykernel\__main__.py:35: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
答案 0 :(得分:0)
嗯,我对你的第一个任务不太确定,但我认为这会对你有帮助。
import pandas as pd
reader = pd.read_csv(path,engine='python')
reader['new'] = reader['treasury.maturity.rate']+reader['bond.yield']
reader.to_csv('test.csv',index=False)
正如您所看到的,您不需要在使用它们之前获取值,只需引用它们所在的列;并且只对特定行执行相同的操作,您可以在创建新列之前过滤数据帧。