Home > database >  Splitting dataframe into multiple dataframe
Splitting dataframe into multiple dataframe

Time:02-21

I have a dataframe of 6 days. I want to split the dataframe for every 2 days and create new dataframe.How to do it ?. Thanks in advance

enter image description here

CodePudding user response:

First of all, let's treat your "filename" column as a datetime:

df["filename"] = pd.to_datetime(df["filename"])

Now, using pandas.Grouper you can group your data by the frequency you want (2 days):

for _, df_2days in df.groupby(pd.Grouper(key="filename", freq="2D")):
    # Each `df_2days` object is a dataframe with only rows of a 2 days range
    print(df_2days)

If you want to unpack the values (assuming that you'll always receive 3 groups), you can do this:

(_, df1), (_, df2), (_, df3) = df.groupby(pd.Grouper(key="filename", freq="2D"))

The _ variable is a common name for values that can be ignored (is a convention). Because each group is a tuple of index name and dataframe, and since you only want the dataframe, we can ignore the first value of each of the 3 tuples.

  • Related