我正在尝试遍历数据框并删除“ player_fifa_api_id”列中的值等于上一行中的值的行。由于某些原因,我的代码无法正常工作:
for i in range(0,len(test)-1):
print("{} lines out of {} processed".format(i,len(test)))
if test['player_fifa_api_id'].iloc[i+1] == test['player_fifa_api_id'].iloc[i]:
test.drop(test.index[i])
有人知道我要去哪里错吗? 这是数据框格式Locator Strategies
的屏幕截图答案 0 :(得分:3)
您应避免循环访问数据框。使用矢量化函数通常会有更快,更优雅的解决方案。对于您的情况,请过滤所需的行:
player_id = test['player_fifa_api_id']
# if the current row is not equal to the previous row, then keep the current row
keep = player_id != player_id.shift()
# filter for the rows you want to keep
result = test[keep]
答案 1 :(得分:1)
为什么不使用drop_duplicates代替:
import pandas as pd
test.drop_duplicates(subset='player_fifa_api_id', keep='first', inplace=True)