我想从同一数据帧的特定单元格的另一个值中分配特定单元格的一个值。
我尝试过以下几种:
df.loc[i_list[0]][first_empty_column_unique] = df.iloc[i][index_of_duplicate_element]
但我得到了以下错误:
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
我也试着复制df如下:
elements = df.iloc[i][[index_of_duplicate_element]].copy()
df.loc[i_list[0]][first_empty_column_unique] = elements
但我还是犯了错误。
在我的情况下,从一个单元格复制到另一个单元格的正确方式是什么?
通常使用loc
时,您应该编写.loc[x, y]
而不是.loc[x][y]
(与iloc
相同(:
df.loc[i_list[0], first_empty_column_unique] = df.iloc[i, index_of_duplicate_element]
我不得不处理类似的问题
richardec的答案显示了如何修复
但是,如果你也很好奇为什么它没有像你预期的那样工作,警告也会重定向到解释问题的文档页面:
https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#indexing-查看与复制
长话短说,当您使用双大括号时,索引分两步完成(按行和按列(,最终可能会对原始文件的副本进行操作
相反,当您一次性使用loc函数时,会执行多索引(行和列(,从而确保更改将影响原始数据帧:
df.loc['row_index']['Column'] = 'SomeValue' #will raise the warning and might not work
df.loc['row_index', 'Column'] = 'SomeValue' #won't raise the warning and works perfectly
````