将整个列设置为值Pandas的Pythonic方法(SettingWithCopyWarning) [英] Pythonic way to set entire column to value Pandas (SettingWithCopyWarning)

查看:111
本文介绍了将整个列设置为值Pandas的Pythonic方法(SettingWithCopyWarning)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将整个列设置为单个字符串值.这样做时,我得到了(曾经如此受欢迎的)SettingWithCopy.在发布有关特定问题的信息之前,我尝试过搜索SO.

I want to set an entire column to a single string value. When doing so I get the (ever so popular) SettingWithCopy. I've tried to search SO before posting about this specific issue.

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摆脱警告,但是我觉得那是作弊".我正在看文档,但是找不到在不添加.copy()或不显示警告的情况下将整个列设置为单个值的最小方法.最好的方法是什么?

And I know I can get rid of the warning with pd.options.mode.chained_assignment = None but I feel like that's "cheating". I'm looking at the documentation, but can't find a minimal way for setting an entire column to a single value without adding .copy() or suppressing the warning. What's the best way to do that?

推荐答案

我今天早些时候正在研究类似的要求,并且遇到了

I was working on a similar requirement earlier today and I came across assign. I got rid of the copy warning without using pd.options.mode.chained_assignment = None. Here was my solution:

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参数.因此,只需重新分配对我有用的价值即可.

assign will leave a copy of the dataframe, and there is no inplace=True parameter. so just reassigning the value worked for me.

这篇关于将整个列设置为值Pandas的Pythonic方法(SettingWithCopyWarning)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆