【问题标题】:Pandas get unique values in one column based off of another column python熊猫在基于另一列python的一列中获得唯一值
【发布时间】:2021-06-22 23:45:04
【问题描述】:

这里我有一个如下的数据框:

Variable    Groups
1           [0-10]
1           [0-10]
2           [0-10]
2           [0-10]
3           [0-10]
3           [10-20]
4           [10-20]
4           [10-20]
5           [10-20]
5           [10-20]

我只想获取 Variable 列的唯一值,但不想丢失不同 Groups 中的任何重复项,例如:

Variable    Groups
1           [0-10]
2           [0-10]
3           [0-10]
3           [10-20]
4           [10-20]
5           [10-20]

请注意,仍然存在重复的 3,因为每个组中都有一个。我试过了

df_unique = df['Groups'].groupby(df['Variable']).unique().apply(pd.Series)

但这只是返回一团糟。不知道该怎么做,感谢帮助。

【问题讨论】:

    标签: python pandas dataframe unique


    【解决方案1】:

    您可以将SeriesGroupBy.unique().explode().reset_index()一起使用,如下:

    df.groupby('Variable')['Groups'].unique().explode().reset_index()
    

    另一种解决方法是使用GroupBy.first(),如下:

    df.groupby(['Variable', 'Groups'], as_index=False).first()
    

    结果:

       Variable   Groups
    0         1   [0-10]
    1         2   [0-10]
    2         3   [0-10]
    3         3  [10-20]
    4         4  [10-20]
    5         5  [10-20]
    
    

    【讨论】:

      【解决方案2】:

      这是另一种选择:

      df.groupby(['variable',df['groups'].explode()]).head(1)
      

      【讨论】:

      • 这里不需要使用.explode()。没有效果。
      • 我相信你不能 groupby 列表,所以 explode 使它们成为对象 dtype。
      【解决方案3】:

      您需要编写一个组合两列的表达式,并将unique 应用于组合。

      【讨论】:

        猜你喜欢
        • 2020-10-01
        • 2018-02-18
        • 1970-01-01
        • 1970-01-01
        • 2021-10-05
        • 2013-08-01
        • 2015-01-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多