【发布时间】: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