问题
I have a set of attribute,value pairs like this:
date,01-01-2018
product,eggs
price, 5
date,01-10-2018
product,milk
price,3
And I want to create a table like
date,product,price
01-01-2018,eggs,5
01-10-2018,milk,3
I've tried adding headers 'attributes' and attribute_values', creating an arbitrary column "values" and using
pd.pivot_table(av_pairs, index="value", columns=av_pairs.attributes, values=av_pairs.attribute_values)
The error is
pandas.core.base.DataError: No numeric types to aggregate
Using stack() also didn't work. Can anyone point out what I'm looking for?
回答1:
Use pandas.pivot and count new indices by 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'])
Or use set_index with unstack:
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
来源:https://stackoverflow.com/questions/53190981/use-pandas-pivot-table-to-convert-attribute-value-pairs-to-table