【问题标题】:Select first row when there are multiple rows with repeated values in a column [duplicate]当一列中有多行重复值时选择第一行[重复]
【发布时间】:2020-02-19 06:57:34
【问题描述】:

当一列中有多行重复值时,我想选择第一行。

例如:

import pandas as pd
df = pd.DataFrame({'col1':['one', 'one', 'one', 'one', 'one', 'one', 'one', 'one'], 
                   'col2':['ID=ABCD1234', 'ID=ABCD1234', 'ID=ABCD1234', 'ID=ABCD5678', 
                           'ID=ABCD5678', 'ID=ABCD5678', 'ID=ABCD9102', 'ID=ABCD9102']})

pandas 数据框如下所示:

print(df)
  col1         col2
0  one  ID=ABCD1234
1  one  ID=ABCD1234
2  one  ID=ABCD1234
3  one  ID=ABCD5678
4  one  ID=ABCD5678
5  one  ID=ABCD5678
6  one  ID=ABCD9102
7  one  ID=ABCD9102

我希望选择第 0 行、第 3 行和第 6 行并将其作为新数据帧输出。

预期输出:

      col1         col2
    0  one  ID=ABCD1234
    3  one  ID=ABCD5678
    6  one  ID=ABCD9102

【问题讨论】:

  • 使用df = df.drop_duplicates()

标签: python pandas dataframe


【解决方案1】:

只需按行的值分组并使用first() 选择第一行:

df.groupby('col2').first()

您也可以决定按多列分组:

df.groupby(['col1', 'col2']).first()

【讨论】:

  • 我喜欢这个解决方案,因为语法优雅。
【解决方案2】:

你可以使用:

df.drop_duplicates(subset = ['col2'], keep = 'first', inplace = True) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 2014-03-03
    • 2017-07-24
    • 2017-12-18
    • 2018-03-16
    • 2016-07-22
    相关资源
    最近更新 更多