Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Splitting dataframe into multiple dataframe

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading