TransWikia.com

How to split pieces of dataframe and create new dataframes based on it?

Data Science Asked by Fernando Tanoue on December 7, 2020

I have the following dataframe that I need to split bu Product and create a new dataframe for each product contain the series ds and y. How can I do that?

enter image description here

enter image description here

One Answer

One way of doing this is explained here, for example:

import pandas as pd 
import numpy as np

df = pd.DataFrame([('bird', 'Falconiformes', 389.0),
                   ('bird', 'Psittaciformes', 24.0),
                   ('mammal', 'Carnivora', 80.2),
                   ('mammal', 'Primates', np.nan),
                   ('mammal', 'Carnivora', 58)],
                   columns=('class', 'order', 'max_speed'))

Simply do the following, would return groupby separated dataframe, stored in a list:

dfs = [x for _, x in df.groupby('class')]

#dfs
[  class           order  max_speed
 0  bird   Falconiformes      389.0
 1  bird  Psittaciformes       24.0,
     class      order  max_speed
 2  mammal  Carnivora       80.2
 3  mammal   Primates        NaN
 4  mammal  Carnivora       58.0]

Please note here you should lookup via list index not the class names, for example df[0]:

   class    order           max_speed
0   bird    Falconiformes   389.0
1   bird    Psittaciformes  24.0

And df[1] the other class!

Answered by TwinPenguins on December 7, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP