简体   繁体   English

按除第一列以外的所有列分组,但聚合为列出第一列

[英]Group by the all the columns except the first one, but aggregate as list the first column

Let's say, I have this dataframe:比方说,我有这个 dataframe:

df = pd.DataFrame({'col_1': ['yes','no'], 'test_1':['a','b'], 'test_2':['a','b']})

What I want, is to group by all the columns except the first one and aggregate the results where the group by is the same.我想要的是对除第一列以外的所有列进行分组,并汇总分组依据相同的结果。

This is what I'm trying:这就是我正在尝试的:

col_names = df.columns.to_list()

df_out = df.groupby([col_names[1:]])[col_names[0]].agg(list)

This is my end data frame goal:这是我的最终数据框目标:

df = pd.DataFrame({'col_1': [['yes','no']], 'test_1':['a'], 'test_2':['b']})

And, if I have more rows, I want it to behave with the same principle, join in list the groups that are the same based on the column [1:] (from the second till end.而且,如果我有更多行,我希望它以相同的原则运行,加入基于列 [1:] 的相同组列表(从第二个到最后。

Using pandas agg() method使用 pandas agg()方法

df = df.groupby(df.columns.difference(["col_1"]).tolist()).agg(
    lambda x: x.tolist()).reset_index()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将所有列加倍,除了第一列和最后一列 - Double all columns except for the first and the last one 如何将DataFrame中除第一列之外的所有列合并为一列,并删除空行? 蟒蛇 - How to merge all columns in a DataFrame except the first into one column and drop empty rows? Python 如何更改Pandas中除第一列之外的所有列的列类型? - How to change the column type of all columns except the first in Pandas? 将所有行更改为与第一行具有相同的数据,但一列除外 - Changing all rows to have same data as first except for one column 增加列表的所有元素,除了 Python 中的第一个元素 - Increase all elements of a list except the first one in Python 按一列分组,然后在两列中查找熊猫 - Group by one column and find first of two columns pandas 大熊猫:shift(1)组中的所有值,但第一个值(每组中的第一个除外)应为0 - pandas: shift(1) all values in group, except first one (in each group) which should be 0 熊猫根据第一列以外的所有现有列的值创建新列 - Pandas create new columns base on all existing columns' values, except the first column 除第一列(索引列或纪元日期时间)外,所有列均乘以100 - multiply all columns by 100 except first column ( index column or the epoch datetime ) 如何更换除第一个以外的所有出现? - How to replace all occurences except the first one?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM