【问题标题】:Grouping By 2 Columns In Pandas Ignoring Order在 Pandas 中按 2 列分组忽略顺序
【发布时间】:2021-10-31 04:41:45
【问题描述】:

我在 Pandas 中有一个 Dataframe,其中有 2 列几乎相同但不完全相同,因此有时我想按两列分组而忽略顺序。

举个例子:

mydf = pd.DataFrame({'Colour1': ['Red', 'Red', 'Blue', 'Green', 'Blue'], 'Colour2': ['Red', 'Blue', 'Red', 'Blue', 'Green'], 'Rating': [4, 5, 7, 8, 2]})
  Colour1 Colour2  Rating
0     Red     Red       4
1     Red    Blue       5
2    Blue     Red       7
3   Green    Blue       8
4    Blue   Green       2

我想按 Colour1 和 Colour2 分组,同时忽略顺序,然后通过取平均值来转换 Dataframe 以生成以下 Dataframe:

  Colour1 Colour2  Rating  MeanRating
0     Red     Red       4           4
1     Red    Blue       5           6
2    Blue     Red       7           6
3   Green    Blue       8           5
4    Blue   Green       2           5

有什么好的方法吗?提前致谢。

【问题讨论】:

    标签: python-3.x pandas dataframe pandas-groupby


    【解决方案1】:

    您可以先使用 np.sort 对 column1 和 2 进行排序,然后使用 groupby:

    s = pd.Series(map(tuple,np.sort(mydf[['Colour1','Colour2']],axis=1)),index=mydf.index)
    mydf['MeanRating'] = mydf['Rating'].groupby(s).transform('mean')
    

    print(mydf)
    
      Colour1 Colour2  Rating  MeanRating
    0     Red     Red       4           4
    1     Red    Blue       5           6
    2    Blue     Red       7           6
    3   Green    Blue       8           5
    4    Blue   Green       2           5
    

    【讨论】:

      猜你喜欢
      • 2020-11-16
      • 2014-05-13
      • 2019-04-05
      • 2019-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多