pandas根据datafram的两个独立列中的值构造列

2024-09-29 19:21:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个与此类似的pandas数据帧(我编写了一个示例,因为我无法共享数据)

raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Scouts'], 
        'company': ['1st', '2nd', '1st', '2nd', '2nd'],  
        'thisValue': [1, 2, 3, 2, 7],
        'total': [3, 3, 5, 5, 7]}
df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'thisValue', 'total'])
df

输出为:

    regiment    company thisValue   total
0   Nighthawks  1st         1         3
1   Nighthawks  2nd         2         3
2   Dragoons    1st         3         5
3   Dragoons    2nd         2         5
4   Scouts      2nd         7         7

我想统计一个团每个值的数值。也就是说,我需要得到如下的数据帧:

regiment    1stCompanyValue 2nd_Company_Value   total
Nighthawks         1               2              3
Dragoons           3               2              5
Scouts             0               7              7

我试着根据公司的价值观来分类,但不知道该怎么做。如何在熊猫身上做到这一点


Tags: 数据示例dataframepandasdfdatarawcompany
1条回答
网友
1楼 · 发布于 2024-09-29 19:21:18

我们可以利用^{}^{}^{},即

one  = df.pivot(columns='company',values='thisValue',index='regiment').add_suffix('_company_value').fillna(0)
two = df.groupby('regiment')['total'].first()

ndf = pd.concat([one,two],1)

              1st_company_value  2nd_company_value  total
regiment                                               
Dragoons                  3.0                2.0      5
Nighthawks                1.0                2.0      3
Scouts                    0.0                7.0      7

相关问题 更多 >

    热门问题