【问题标题】:In python, convert pandas "one to many" dataset transposing rows to columns在python中,将pandas“一对多”数据集转换为列
【发布时间】:2021-06-27 10:13:37
【问题描述】:

我有两个“一对多”格式的 Python 数据集,由 ID 列链接。

df1 = pd.DataFrame({'id': [1, 2],
                    'mandante': ['flamengo', 'botafogo'],
                    'visitante': ['ceara', 'são paulo'],
                     'vencedor': ['mandante', 'visitante']})

df2 = pd.DataFrame({'id': [1,1,2,2],
                    'tipo': ['mandante', 'visitante', 'mandante', 'visitante'],
                    'posse':['25%', '75%', '50%', '50%'],
                    'pontos': [25, 20, 14, 10]})

我想加入这个数据集,但是为 DF2 的每两行添加列到 DF1 数据集,创建一个新的数据集,其中包含由名称中的“tipo”列吃掉的 DF2 数据集的行组成的列...

非常感谢!!!

【问题讨论】:

  • 输出是否正确?
  • 我只是一个小错误:)

标签: python pandas dataframe dataset


【解决方案1】:

DataFrame.pivotMultiIndex 的扁平列一起使用:

df2 = df2.pivot(index='id',columns='tipo')
#alternative
#df2 = df2.set_index(['id','tipo']).unstack()
df2.columns = df2.columns.map(lambda x: f'{x[0]}_{x[1]}')

print (df2)
   posse_mandante posse_visitante  pontos_mandante  pontos_visitante
id                                                                  
1             25%             75%               25                20
2             50%             50%               14                10

然后将DataFrame.join添加到df1

df = df1.join(df2, on='id')
print (df)
   id  mandante  visitante   vencedor posse_mandante posse_visitante  \
0   1  flamengo      ceara   mandante            25%             75%   
1   2  botafogo  são paulo  visitante            50%             50%   

   pontos_mandante  pontos_visitante  
0               25                20  
1               14                10  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 2014-08-19
    • 2021-11-09
    • 1970-01-01
    相关资源
    最近更新 更多