在熊猫数据框中连接行-新版本

问题描述 投票:0回答:1

我有下表。

import pandas as pd
# Define the input data
data = {
    'ID': [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3],
    'count': [1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,1,1,1,1,2,2,1,1,1,1,2],
    'priority': [1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,4,3,1,2,3,4,4],
    'item': ['A','B','C','D','A','B','C','D','A','B','C','D','A','B','C','D','A','B','C','D','D','C','A','B','C','D','D'],
    'c': ['XX','XX','XX','XX','YY-SS','YY','YY','YY','YY-SS','YY','YY','YY','XX','XX','XX','XX','ZZ','ZZ','ZZ','ZZ','ZZ','ZZ','TT-SS','ZZ','ZZ','ZZ','ZZ']
}

# Convert the input data to a Pandas DataFrame
df = pd.DataFrame(data)

我需要转换这个输入,你可以在下面的输出示例中看到:在此处输入图像描述

如果您有任何想法,请分享。非常感谢!

pandas dataframe concatenation data-manipulation
1个回答
1
投票

您可以使用自定义

groupby.agg

out = (df
   .sort_values(by='priority') # optional
   .groupby(['ID', 'count'], as_index=False)
   .agg({'item': '-'.join, 'c': 'first'})
   .assign(FINAL=lambda d: d.pop('item')+'-'+d.pop('c'))
   .drop(columns='count')
)

输出:

   ID          FINAL
0   1     A-B-C-D-XX
1   1  A-B-C-D-YY-SS
2   1  A-B-C-D-YY-SS
3   1     A-B-C-D-XX
4   2     A-B-C-D-ZZ
5   2         D-C-ZZ
6   3  A-B-C-D-TT-SS
7   3           D-ZZ
© www.soinside.com 2019 - 2024. All rights reserved.