Home > Backend Development > Python Tutorial > How Can I Split a Pandas DataFrame into Multiple DataFrames Based on Column Values Using Groupby?

How Can I Split a Pandas DataFrame into Multiple DataFrames Based on Column Values Using Groupby?

Patricia Arquette
Release: 2024-12-19 09:19:16
Original
975 people have browsed it

How Can I Split a Pandas DataFrame into Multiple DataFrames Based on Column Values Using Groupby?

Splitting a Pandas DataFrame Based on Column Values Using Groupby

Pandas offers the powerful groupby function to manipulate data based on common values in a specified column. One practical application of this function is splitting a DataFrame into multiple smaller DataFrames based on unique values in a column.

Consider the DataFrame df below:

df = 
        N0_YLDF  ZZ        MAT
    0  6.286333   2  11.669069
    1  6.317000   6  11.669069
    2  6.324889   6  11.516454
    3  6.320667   5  11.516454
    4  6.325556   5  11.516454
    5  6.359000   6  11.516454
    6  6.359000   6  11.516454
    7  6.361111   7  11.516454
    8  6.360778   7  11.516454
    9  6.361111   6  11.516454
Copy after login

To split this DataFrame into four DataFrames based on the unique values of column ZZ, follow these steps:

  1. Group the DataFrame by column ZZ:

    gb = df.groupby('ZZ')
    Copy after login
  2. Obtain a list of grouped objects:

    grouped_objects = [gb.get_group(x) for x in gb.groups]
    Copy after login

The result will be a list of four DataFrames, each representing a different group based on the unique values in column ZZ.

The above is the detailed content of How Can I Split a Pandas DataFrame into Multiple DataFrames Based on Column Values Using Groupby?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template