pandas按组转置数字

时间:2016-10-17 17:06:58

标签: python pandas pivot pivot-table transpose

制作测试数据的代码

import pandas as pd

dftest = pd.DataFrame({'Amt': {0: 60, 1: 35.0, 2: 30.0, 3: np.nan, 4: 25},
                       'Year': {0: 2012.0, 1: 2012.0, 2: 2012.0, 3: 2013.0, 4: 2013.0},
                       'Name': {0: 'A', 1: 'A', 2: 'C', 3: 'A', 4: 'B'}})

给出

    Amt     Name    Year
0   60        A   2012.0
1   35.0      A   2012.0
2   30.0      C   2012.0
3   NaN       A   2013.0
4   25        B   2013.0

Amt的最多2个值对应于组['Name', 'Year']。我想转动/转置,使输出的格式为

       Name  Year   Amt1  Amt2
0         A  2012   35    60
2         C  2012   30    NaN
3         A  2013   NaN   NaN
4         B  2013   25    NaN

我尝试过使用pivot,unstack,pivot_table

我真正想要做的是确保Amt['Name', 'Year']有两个值NApublic class Driver { public Driver(TextBox moduleName, TextBox dynamicNumber) { textBox_ModuleName = moduleName; textBox_DynamicNumber = dynamicNumber; textBox_ModuleName.DataBindings.Add("Text", this, "ModuleName"); textBox_DynamicNumber.DataBindings.Add("Text", this, "DynamicNumber"); } public string ModuleName { get; set; } public string DynamicNumber { get; set; } private TextBox textBox_ModuleName; private TextBox textBox_DynamicNumber; } &#39}可以),我可以通过堆叠期望的输出

1 个答案:

答案 0 :(得分:3)

使用groupbyapply

f = lambda x: x.sort_values(ascending=True).reset_index(drop=True)
dftest.groupby(['Name', 'Year']).Amt.apply(f).unstack()

enter image description here