使用pandasivot_table()将属性值对转换为表

时间:2018-11-07 14:00:40

标签: python pandas

我有一组属性,值对如下:

date,01-01-2018
product,eggs
price, 5
date,01-10-2018
product,milk
price,3

我想创建一个像这样的表

date,product,price
01-01-2018,eggs,5
01-10-2018,milk,3

我尝试添加标头'attributes'和attribute_values',创建任意列“ values”并使用

pd.pivot_table(av_pairs, index="value", columns=av_pairs.attributes, values=av_pairs.attribute_values)

错误是

pandas.core.base.DataError: No numeric types to aggregate

使用stack()也不起作用。谁能指出我在寻找什么?

1 个答案:

答案 0 :(得分:1)

使用pandas.pivot并按cumcount计算新索引:

print (df)
         a           b
0     date  01-01-2018
1  product        eggs
2    price           5
3     date  01-10-2018
4  product        milk
5    price           3

df1 = pd.pivot(index=df.groupby('a').cumcount(),
              columns=df['a'],
              values=df['b'])

或将set_indexunstack一起使用:

df1 = df.set_index([df.groupby('a').cumcount(), 'a'])['b'].unstack()

print (df1)
a        date price product
0  01-01-2018     5    eggs
1  01-10-2018     3    milk