-1

I have Data looking like this:

Animal Day Food kg
1      1   17   0.1
1      1   22   0.7
1      2   17   0.8
2      2   15   0.1

I would like to have a table looking like this:

Animal Food Day1 Day2 ...
1      17   0.1  0.8  ...
1      22   0.7       ...
2      15        0.1

I was able to make it work on a small data set with copying the dataframe and merging the copies. However this seems very inefficient to me. So I was wondering what would be done to make it work on a bigger data set?

MatheMarco
  • 13
  • 2
  • 1
    What dataframe library are you using? For reference, this type of operation is typically called a "pivot". – 0x5453 Sep 22 '21 at 12:54
  • I am using pandas – MatheMarco Sep 22 '21 at 12:55
  • Does this answer your question? [Python Pandas: Convert Rows as Column headers](https://stackoverflow.com/questions/17298313/python-pandas-convert-rows-as-column-headers) – Maaz Sep 22 '21 at 12:57

1 Answers1

1

Try with pivot:

output = df.pivot(["Animal", "Food"], "Day", "kg") \
           .add_prefix("Day") \
           .reset_index() \
           .rename_axis(None, axis=1)

>>> output
   Animal  Food  Day1  Day2
0       1    17   0.1   0.8
1       1    22   0.7   NaN
2       2    15   NaN   0.1
not_speshal
  • 20,086
  • 2
  • 13
  • 28