Pandas DataFrame:SettingWithCopyWarning:试图在DataFrame的切片副本上设置一个值 [英] Pandas DataFrame: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
问题描述
我知道关于此警告的帖子很多,但是我找不到解决我的情况的解决方案.这是我的代码:
I know there are tons of posts about this warning, but I couldn't find a solution to my situation. Here's my code:
df.loc[:, 'my_col'] = df.loc[:, 'my_col'].astype(int)
#df.loc[:, 'my_col'] = df.loc[:, 'my_col'].astype(int).copy()
#df.loc[:, 'my_col'] = df['my_col'].astype(int)
它会产生警告:
SettingWithCopyWarning:试图在一个副本上设置一个值 从DataFrame切片.尝试使用.loc [row_indexer,col_indexer] = 值代替
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
即使我按建议更改了代码,仍然收到此警告?我需要做的就是转换一列的数据类型.
Even though I changed the code as suggested, I still get this warning? All I need to do is to convert the data type of one column.
**备注:**最初,该列是float类型,具有一个小数点(例如:4711.0).因此,我将其更改为整数(4711),然后更改为字符串('4711')-只是为了删除小数.
**Remark: ** Originally the column is of type float having one decimal (example: 4711.0). Therefore I change it to integer (4711) and then to string ('4711') - just to remove the decimal.
感谢您的帮助!
更新:警告是对之前进行的原始数据过滤的副作用.我错过了DataFrame.copy().改用副本即可解决问题!
Update: The warning was a side effect on a filtering of the original data that was done just before. I was missing the DataFrame.copy(). Using the copy instead, solved the problem!
df = df[df['my_col'].notnull()].copy()
df.loc[:, 'my_col'] = df['my_col'].astype(int).astype(str)
#df['my_col'] = df['my_col'].astype(int).astype(str) # works too!
推荐答案
我认为需要 说明:
如果以后在df
中修改值,您会发现修改不会传播回原始数据(df
),并且Pandas会发出警告.
If you modify values in df
later you will find that the modifications do not propagate back to the original data (df
), and that Pandas does warning.
这篇关于Pandas DataFrame:SettingWithCopyWarning:试图在DataFrame的切片副本上设置一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!