pandas - 熊猫将索引复制到新列
问题描述
我正在尝试使用此处的答案将数据框 () 的索引复制newdf
到新列 ( )但收到了臭名昭著的. 我在这里尝试了答案,它说要添加,但会引发更多警告。所有错误都在代码的最后一行抛出;如果代码在创建时停止,则不会出现错误。temp_index
SettingWithCopyWarning
.loc[:, colname]
newdf
复制索引的正确方法是什么?宁愿不重置索引,我希望索引来自df
并且newdf
是可以接受的。我只需要复制列来做其他事情。
示例可重现代码
col1 = [0,1,1,0,0,0,1,1,1]
col2 = [1,5,9,2,4,2,5,6,1]
df = pd.DataFrame(list(zip(col1, col2)), columns =['col1', 'col2'])
newdf = df[df.col2 >= 3]
display(df, newdf)
newdf.loc[:, 'temp_index'] = newdf.index
错误
C:\Users\...\lib\site-packages\pandas\core\indexing.py:845: 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
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
self.obj[key] = _infer_fill_value(value)
C:\Users\...\lib\site-packages\pandas\core\indexing.py:966: 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
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
self.obj[item] = s
解决方案
temp_index
您在最后一行中设置列的方式没有任何问题。问题正如警告中所说的那样。你到底想达到什么目的?要避免此警告,请执行此操作newdf = df[df.col2 >= 3].copy()
。请注意,您正在使用布尔键进行索引,AFAIK 无论如何都会创建一个副本,因此上述内容不会增加您的内存占用。如果您实际上想将索引插入df
但仅插入行的子集,请尝试
key = df.col2 >= 3
df = df.loc[key, 'temp_index'] = df.index[key]
推荐阅读
- php - 是否可以在 PHPDoc 的调用方中为参数指定显式类型
- google-bigquery - 多次成功查询后,批处理作业偶尔会出现“没有 bigquery.jobs.create 权限”错误
- c# - SquidCoin.cs 我的货币脚本在添加 [PlayerPrefs] 后不起作用
- sql - PostgreSQL:意外的数组元素
- c# - ASP.Net Core 2.1 中的自定义授权过滤器与策略
- visual-studio - 将 SSRS 从 2016 年降级至 2008 年
- android - 具有上一页和下一页边界的 RecyclerView?
- php - 一个php页面中的MYSQL多选查询
- azure-active-directory - 带有 Azure AD 的身份服务器
- ios - 为 collectionView 中的每个其他项目设置特定布局