簡體   English   中英

pandas數據框基於對其他列的計算來添加新列,並避免鏈接索引

[英]pandas dataframe add new column based on calulation on other column and avoid chained index

我有一個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

上面的代碼有2個問題:

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

好吧,我不太確定您的第一個任務,但我認為這會對您有所幫助。

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)

如您所見,在使用它們之前,無需獲取值,只需引用它們所在的列即可。 並僅對特定行執行相同操作,則可以在創建新列之前過濾數據框。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM