Home > Enterprise >  Big Data Manipulations with Python
Big Data Manipulations with Python

Time:09-24

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?

CodePudding user response:

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
  • Related