Pivot Function in Python

The pivot() function is used to reshape a given DataFrame organized by given index / column values. This function does not support data aggregation, multiple values will result in a MultiIndex in the columns.

import numpy as np

import pandas as pd

df = pd.DataFrame({‘fff’: [‘one’, ‘one’, ‘one’, ‘two’, ‘two’, ‘two’], ‘bbb’: [‘P’, ‘Q’, ‘R’, ‘P’, ‘Q’, ‘R’], ‘baa’: [2, 3, 4, 5, 6, 7], ‘zzz’: [‘h’, ‘i’, ‘j’, ‘k’, ‘l’, ‘m’]})

fff | bbb | baa | zzz | |
---|---|---|---|---|

0 | one | P | 2 | h |

1 | one | Q | 3 | i |

2 | one | R | 4 | j |

3 | two | P | 5 | k |

4 | two | Q | 6 | l |

5 | two | R | 7 | m |

~ df.pivot(index=‘fff’, columns=‘bbb’, values=‘baa’)

bbb | P | Q | R |
---|---|---|---|

fff | |||

one | 2 | 3 | 4 |

two | 5 | 6 | 7 |

df.pivot(index=‘fff’, columns=‘bbb’, values=[‘baa’, ‘zzz’])

bbb | P | Q | R | P | Q | R |
---|---|---|---|---|---|---|

fff | ||||||

one | 2 | 3 | 4 | h | i | j |

two | 5 | 6 | 7 | k | l | m |