pandas - 根据数据帧的2个独立列中的值构造列

时间:2017-12-06 13:07:47

标签: python pandas dataframe pivot

我有一个类似于此的pandas数据框(我已经编写了一个例子,因为我无法共享数据)

    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

我希望得到关于团的每个值的计数的统计数据。那就是我需要得到的数据帧如下:

<modal v-if="showModal" :my-data="myData" @close="showModal = false">

我尝试将其分组为公司值,但后来不确定如何继续。怎么能在熊猫里做到这一点?

1 个答案:

答案 0 :(得分:2)

我们可以使用pivotgroupbyconcat,即

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