简体   繁体   English

使用GroupBy向数据框添加新列

[英]Using GroupBy to add new columns to data frame

I have a data frame like so 我有一个像这样的数据框架

id val1 val2
0   A    B
1   C    D
1   E    F
2   G    H

and trying to reshape into... 并试图重塑成......

id val1 val2 val3 val4
0   A    B
1   C    D    E    F
2   G    H

It doesn't matter what the additional column names are and I may not know how many duplicates there are of each id, so I may not know exactly how many columns to add. 附加列名称是什么并不重要,我可能不知道每个id有多少重复,所以我可能不知道要添加多少列。

Any advice for solving a problem like this? 有什么建议可以解决这样的问题吗? I've been trying to use pandas and groupBy, but I'm not constrained to either. 我一直在尝试使用pandas和groupBy,但我也不会受到限制。 Thanks! 谢谢!

This is a pivot problem, but you'll need to convert your frame from wide to long before you can pivot it: 这是一个pivot问题,但您需要将框架从宽到长转换为可以转动它:

u = df.melt('id')
u.assign(variable=u.groupby('id').cumcount()).pivot(*u)

variable  0  1    2    3
id                      
0         A  B  NaN  NaN
1         C  E    D    F
2         G  H  NaN  NaN

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

相关问题 从pandas数据框中提取计数以外的新列groupby - Extracting new columns with counts out of pandas data frame groupby 如何将数据框作为新列添加到其他数据框? - how to add a data frame to an other data frame as new columns? 如果日期在其他两个列中的两个日期之间,则求和并分组并创建新的分组数据框 - pandas - Sum and groupby if date is between two dates in two other columns and create new groupby data frame - pandas 使用 Groupby 将数据框列放入列表列表 - Data-frame columns into list of lists using Groupby 使用 groupby 将数据框拆分为具有不同列的多个数据框 - Splitting dataframes into multiple data frame with differing columns using groupby 使用groupby拆分数据帧并将子集合并为列 - Split a data frame using groupby and merge the subsets into columns Pandas - 使用Groupby列出新列中的数据列 - Pandas - List out data columns in new columns using Groupby 尝试使用 Pandas 数据框中其他两列的 groupby 基于另一列创建新的滚动平均列时出错 - Error when trying to create new rolling average column based on another column using groupby of two other columns in pandas data frame 熊猫:使用多个GroupBy结果创建一个新的数据框 - Pandas: Create a new Data Frame using multiple GroupBy results 如何在Pandas中使用groupby有效地添加新列? - How can I add new columns efficiently using groupby in Pandas?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM