简体   繁体   English

如何通过添加带有熊猫的列将多行合并为单行?

[英]How to combine multiple rows into single row by adding columns with pandas?

I need to combine multiple rows into a single row with pandas, depending on the column 'hash' 我需要将多行与大熊猫合并为一行,具体取决于“哈希”列

View of my dataframe: 我的数据框视图:

    hash     a      b
0     1      1      6
1     1      2      7
2     1      3      8
3     2      4      9 
4     2      5      10

I want the dataframe to be converted like this: 我希望数据帧像这样转换:

   hash     a      a1     a3     b     b1     b2  
0    1      1      2      3      6     7      8   
1    2      4      5      nan    9     10     nan 

I have tried to use some code related to groupby or transpose the whole dataframe but cant figure out how to do it. 我试图使用一些与groupby相关的代码或转置整个数据帧,但无法弄清楚该怎么做。 Anyone could help me out? 有人可以帮我吗?

Create MultiIndex by set_index with counter column by cumcount , reshape by unstack and flatten Multiindex by map with join : 建立MultiIndexset_index与计数器列cumcount ,通过重塑unstack和扁平Multiindex通过mapjoin

df1 = df.set_index(['hash', df.groupby('hash').cumcount().add(1).astype(str)]).unstack()
df1.columns = df1.columns.map(''.join)
df1 = df1.reset_index()
print (df1)
   hash   a1   a2   a3   b1    b2   b3
0     1  1.0  2.0  3.0  6.0   7.0  8.0
1     2  4.0  5.0  NaN  9.0  10.0  NaN

暂无
暂无

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

相关问题 Pandas - 将多行合并为一行并创建新列 - Pandas- Combine multiple rows into a single row and create new columns 如何基于多列的值将多行与python pandas合并为单行? - How to combine multiple rows into a single row with python pandas based on the values of multiple columns? Pandas:将多行中的数据添加到单行的额外列中 - Pandas: Adding data from multiple rows into extra columns for a single row 如何将多个无序行与大熊猫合并为单个行[CSV文件] - How to combine multiple unordered rows into a single row with pandas [CSV file] 如何在 pandas 中使用 id 将多行合并为一行多列(将具有相同 id 的多条记录聚集到一条记录中) - How to combine multiple rows into a single row with many columns in pandas using an id (clustering multiple records with same id into one record) 如何在 pandas 中将两行组合成单行 - How to combine two rows in single row in pandas 如何在 pandas 中将多行合并为一行 - how to combine multiple rows to one row in pandas 如何使用行字符串的子集在 pandas dataframe 分组中将多行组合成单行 - How to combine multiple rows into a single row in pandas dataframe grouping using a subset of the row string 如何将 pandas'.explode() 与 a.split() 在多列上与单个附加行结合起来 - How can I combine pandas' .explode() with a .split() on multiple columns with a single additional row 将单行中具有多列的数据集分成多行 - 熊猫 - break into multiple rows a dataset with multiple columns in a single row - pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM