Pythonic方法将整列设置为值Pandas(SettingWithCopyWarning)

时间:2017-06-09 20:36:33

标签: python pandas dataframe

我想将整个列设置为单个字符串值。这样做的时候,我得到了(永远如此受欢迎)SettingWithCopy。我在发布特定问题之前尝试搜索过。

import pandas as pd
import numpy as np
dfp = pd.DataFrame({'A' : [1,21,8,44,np.NaN,6,75,8,44,999], 
                    'B' : [1,1,3,5,0,0,np.NaN,9,np.NaN,0], 
                    'C' : ['AA1233445','AA1233445', 'rmacy','Idaho Rx','Ab123455','TV192837','RX','Ohio Drugs','RX12345','USA Pharma'], 
                    'D' : [123456,123456,1234567,12345678,12345,12345,12345678,123456789,1234567,np.NaN],
                    'E' : ['Assign','Assign','Hello','Ugly','Appreciate','Undo','Testing','Unicycle','Pharma','Unicorn',]})
print(dfp)

new_df_to_show_copy = dfp.loc[(dfp['A']>100) |(dfp['E']=='Unicorn')]
new_df_to_show_copy['Reason'] = 'what is with the copy warning'

现在我可以用

摆脱警告
new_df_to_show_copy = dfp.loc[(dfp['A']>100) |(dfp['E']=='Unicorn')].copy() <--Notice copy()
new_df_to_show_copy['Reason'] = 'what is with the copy warning'

而且我知道我可以用pd.options.mode.chained_assignment = None摆脱警告,但我觉得这样做是在欺骗&#34;。我正在查看文档,但无法在不添加.copy()或禁止警告的情况下找到将整列设置为单个值的最小方法。最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

我今天早些时候正在制定类似的要求,我遇到了assign。我在不使用pd.options.mode.chained_assignment = None的情况下摆脱了复制警告。这是我的解决方案:

new_df_to_show_copy = dfp.loc[(dfp['A']>100) |(dfp['E']=='Unicorn')]
new_df_to_show_copy = new_df_to_show_copy.assign(Reason = 'what is with the copy warning')

# output:

       A    B           C   D        E                         Reason
9  999.0  0.0  USA Pharma NaN  Unicorn  what is with the copy warning    

assign会留下数据框的副本,并且没有inplace=True参数。所以只需重新分配给我的价值。