List item
Any ideas how to go from df
id |feature count
A |apples 2
A |oranges 5
A |pears 9
A |mandarines 12
to this df format?
apples oranges pears mandarines
A 2 5 9 12
Tried .T() but no luck
Try this:
df.set_index('feature', append=True).unstack()['count']
Output:
feature apples mandarines oranges pears
A 2 12 5 9
you can pivot the dataframe and rename the index column:
df = pd.DataFrame({
'id': ['A', 'A', 'A', 'A'],
'feature': ['apples', 'oranges', 'pears', 'mandarines'],
'count': [2, 5, 9, 12]
})
wide_df = df.pivot(index='id', columns='feature', values='count').reset_index()
wide_df.index.name = None
print(wide_df)
If id
is the index its just a pivot.
df.pivot(columns='feature', values='count')
feature apples mandarines oranges pears
id
A 2 12 5 9