简体   繁体   English

设置新列时如何不获取 SettingWithCopyWarning

[英]How not to get SettingWithCopyWarning when setting a new column

I have an annoying problem with SettingWithCopyWarning and I don't seem to get rid of the warning.我对 SettingWithCopyWarning 有一个恼人的问题,我似乎没有摆脱警告。 I have a df users like this我有一个这样的df用户

user id     cloud_files 
    1              0
    2              8
    3              1

I would like to add a boolean column of cloud users我想添加一个云用户的boolean专栏

user id     cloud_files     cloud_user  
    1              0           false
    2              8           true  
    3              1           true  

I have tried to do it but I keep getting the SettingWithCopyWarning.我曾尝试这样做,但我不断收到 SettingWithCopyWarning。

users['cloud_user'] = np.where(users['cloud_files']== 0, True, False)
users['cloud_user'] = users['cloud_files']!= 0
users.loc[:,'cloud_user'] = users['cloud_files']!= 0

I have tried copy and reset index but I just can't get rid of the warning.我已经尝试过复制和重置索引,但我无法摆脱警告。 Is there some way to do it without getting this warning or do I just need to set the warning off?有没有办法在不收到此警告的情况下做到这一点,还是我只需要关闭警告?

You can use properties of booleans to directly create your new column because bool(num) will evaluate to True as long the num is non-zero您可以使用布尔值的属性直接创建新列,因为只要 num 非零, bool(num)就会评估为True

df['cloud_user'] = df['cloud_files'].astype(bool)

Result:结果:

>>> df = pd.DataFrame({'user_id':[1,2,3],'cloud_files':[0,8,1]})
>>> df['cloud_user'] = df['cloud_files'].astype(bool)
>>> df
   user_id  cloud_files  cloud_user
0        1            0       False
1        2            8        True
2        3            1        True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM