16

我想打开一个文件,阅读它,将重复项放在文件的两个列中,然后进一步使用没有重复项的文件进行一些计算。为此,我使用 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))

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

4

2 回答 2

27

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)

也看到这个问题

于 2015-08-27T18:49:08.337 回答
2

我认为您.drop_duplicates()实际上是在引起警告。

相反,请确保制作数据框的新副本:

file2 = file1.drop_duplicates(["Var2", "Var3"]).copy()
于 2019-10-25T21:00:30.760 回答