从列中删除数据

2024-09-29 21:35:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从我的数据框中删除一些数据,但只删除“to country”列中存在重复项的行

我的数据框如下所示:

   Year From country To country  Points
0  2016      Albania    Armenia       0
1  2016      Albania    Armenia       2
2  2016      Albania  Australia      12
      Year    From country       To country  Points
2129  2016  United Kingdom  The Netherlands       0
2130  2016  United Kingdom          Ukraine      10
2131  2016  United Kingdom          Ukraine       5

[2132 rows x 4 columns]

我试试这个:

df.drop_duplicates(subset='To country', inplace=True)

结果是:

   Year From country To country  Points
0  2016      Albania    Armenia       0
2  2016      Albania  Australia      12
4  2016      Albania    Austria       0
    Year From country       To country  Points
46  2016      Albania  The Netherlands       0
48  2016      Albania          Ukraine       0
50  2016      Albania   United Kingdom       5

[50 rows x 4 columns]

虽然这确实消除了重复的“To country”条目,但它也删除了“From country”列的所有值。我一定是把drop\u duplicates()用错了,但是熊猫文档并没有帮助我理解为什么它会比我预期的下降更多?你知道吗


Tags: theto数据fromyearcountrypointsunited
2条回答

最简单的解决方案是按“to country”名称分组,并从每个组中选取第一行(或最后一行,如果您愿意):

df.groupby('To country').first().reset_index()
#        To country  Year    From country  Points
#0          Armenia  2016         Albania       0
#1        Australia  2016         Albania      12
#2  The Netherlands  2016  United Kingdom       0
#3          Ukraine  2016  United Kingdom      10

与aryamccarthy的解决方案相比,这个解决方案可以让您更好地控制要保留哪些副本。你知道吗

不,这种行为是正确的假设每一支球队都和另一支球队比赛,它在寻找第一,而且所有这些第一都是“来自”阿尔巴尼亚。你知道吗

根据您下面所说的,您希望保留第0行,而不是第1行,因为它同时重复ToFrom国家。消除这些问题的方法是:

df.drop_duplicates(subset=['To country', 'From country'], inplace=True)

相关问题 更多 >

    热门问题