在 pandas.drop_duplicates 之后重建索引

新手上路,请多包涵

我想打开一个文件,读取它,在文件的两列中删除重复项,然后进一步使用没有重复项的文件进行一些计算。为此,我使用了 pandas.drop_duplicates,它在删除重复项后也会删除索引值。例如,删除第 1 行后,file1 变为 file2:

 file1:
   Var1    Var2    Var3   Var4
0    52     2       3      89
1    65     2       3      43
2    15     1       3      78
3    33     2       4      67

file2:
   Var1    Var2    Var3   Var4
0    52     2       3      89
2    15     1       3      78
3    33     2       4      67

要进一步将 file2 用作数据框,我需要将其重新索引为 0、1、2 …

这是我正在使用的代码:

 file1 = pd.read_csv("filename.txt",sep='|', header=None, names=['Var1', 'Var2', 'Var3', 'Var4'])
file2 = file1.drop_duplicates(["Var2", "Var3"])
# create another variable as a new index: ni
file2['ni']= range(0, len(file2)) # this is the line that generates the warning
file2 = file2.set_index('ni')

尽管代码运行并产生了良好的结果,但重新索引会给出以下警告:

 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 the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  file2['ni']= range(0, len(file2))

我确实检查了链接,但我不知道如何更改我的代码。有想法该怎么解决这个吗?

原文由 Brebenel 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 648
1 个回答

Pandas 有一个内置函数来完成此任务,这将允许您通过另一种更简单的方法避免抛出的错误

而不是添加一个新的序列号列,然后将索引设置为该列,就像您所做的那样:

 file2['ni']= range(0, len(file2)) # this is the line that generates the warning
file2 = file2.set_index('ni')

您可以改用:

 file2 = file2.reset_index(drop=True)

.reset_index() 的默认行为是获取当前索引,将该索引插入数据框的第一列,然后构建一个新索引(我假设这里的逻辑是默认行为使得它非常容易比较旧索引和新索引,对于完整性检查非常有用)。 drop=True 意味着不是将旧索引保留为新列,而是将其删除并用新索引替换它,这似乎是您想要的。

总之,您的新代码可能如下所示

file1 = pd.read_csv("filename.txt",sep='|', header=None, names=['Var1', 'Var2', 'Var3', 'Var4'])
file2 = file1.drop_duplicates(["Var2", "Var3"]).reset_index(drop=True)

也看到这个问题

原文由 cjprybol 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题