1

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

Scott Boston
  • 147,308
  • 15
  • 139
  • 187
rrttllu
  • 21
  • 1

3 Answers3

1

Try this:

df.set_index('feature', append=True).unstack()['count']

Output:

feature  apples  mandarines  oranges  pears
A             2          12        5      9
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
0

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)
Phoenix
  • 1,343
  • 8
  • 10
0

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
SomeDude
  • 13,876
  • 5
  • 21
  • 44
  • SomeDude, thank you for the suggestion. All these suggestions. Phoenix I think comes closest to what I was looking for but I will test all these suggestions to see which is the best option. Thank you for your help!!! – rrttllu Apr 25 '23 at 03:01