【问题标题】:how to select rows in a data frame those are similar on basis of column values如何在数据框中选择基于列值相似的行
【发布时间】:2020-05-30 14:34:51
【问题描述】:

我的数据框是:

col1 col2 col3 col4
'abc' 2    3    4
'asd' 4    5    6
'dfg' 7    5    6
'ghg' 2    3    4
'xyz' 1    3    4

在这里我想找到基于 'col3' 和 'col4' 相似的行(特别是 'col1' 值的列表) 输出:

[[asd,dfg],[abc,ghg,xyz]]

因为这里 asd 和 dfg 有相似的 'col3' 和 'col4' 值分别为 3 和 4

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    您可以在此处使用df.groupby

    df.groupby('col3').col1.apply(list).tolist()
    # [['abc', 'ghg', 'xyz'], ['asd', 'dfg']]
    

    【讨论】:

    • @Kaiser 很高兴为您提供帮助 ;)
    【解决方案2】:

    这样的事情可能会奏效 -

    df['col1'] = df['col1'].str.replace('\'','')
    df.groupby(['col3'])['col1'].apply(list).reset_index()['col1'].tolist()
    [['abc', 'ghg', 'xyz'], ['asd', 'dfg']]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 2019-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多