我已将 csv 读入 pandas 数据框,它有五列。某些行仅在第二列中具有重复值,我想从数据框中删除这些行,但 drop 和 drop_duplicates 都不起作用。
这是我的实现:
#Read CSV
df = pd.read_csv(data_path, header=0, names=['a', 'b', 'c', 'd', 'e'])
print Series(df.b)
dropRows = []
#Sanitize the data to get rid of duplicates
for indx, val in enumerate(df.b): #for all the values
if(indx == 0): #skip first indx
continue
if (val == df.b[indx-1]): #this is duplicate rtc value
dropRows.append(indx)
print dropRows
df.drop(dropRows) #this doesnt work
df.drop_duplicates('b') #this doesnt work either
print Series(df.b)
当我打印出系列 df.b 之前和之后它们的长度相同时,我仍然可以明显地看到重复项。我的实现有问题吗?
最佳答案
如评论中所述,drop
和 drop_duplicates
会创建一个新的 DataFrame,除非提供了 inplace 参数。所有这些选项都有效:
df = df.drop(dropRows)
df = df.drop_duplicates('b') #this doesnt work either
df.drop(dropRows, inplace = True)
df.drop_duplicates('b', inplace = True)
关于python - DataFrame.drop_duplicates 和 DataFrame.drop 不删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25695878/