我想打开一个文件,阅读它,将重复项放在文件的两个列中,然后进一步使用没有重复项的文件进行一些计算。为此,我使用 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))
我确实检查了链接,但我不知道如何更改我的代码。有想法该怎么解决这个吗?