Home > Backend Development > Python Tutorial > How Can I Efficiently Group Consecutive Values in a Pandas DataFrame Column?

How Can I Efficiently Group Consecutive Values in a Pandas DataFrame Column?

DDD
Release: 2024-12-05 04:54:08
Original
451 people have browsed it

How Can I Efficiently Group Consecutive Values in a Pandas DataFrame Column?

Grouping Consecutive Values in Pandas DataFrames

In a DataFrame, you may encounter a column containing consecutive values that you need to group together. For instance, consider the following column with values:

[1, 1, -1, 1, -1, -1]
Copy after login

To efficiently group these values into desired groups like:

[1,1] [-1] [1] [-1, -1]
Copy after login

follow these steps using the Pandas library:

Solution using Custom Series Grouping

You can leverage a custom Series to achieve this grouping. Here's the approach:

import pandas as pd

# Create sample DataFrame
df = pd.DataFrame({'a': [1, 1, -1, 1, -1, -1]})

# Use ne() and cumsum() to create grouping indicator
ind = df['a'].ne(df['a'].shift()).cumsum()

# Group by this indicator
for i, g in df.groupby(ind):
    # Print grouping key
    print(i)
    
    # Print rows in group
    print(g)
    
    # Convert values to list for display
    print(g.a.tolist())
Copy after login

This code will output the desired groupings and values:

1
   a
0  1
1  1
[1, 1]
2
   a
2 -1
[-1]
3
   a
3  1
[1]
4
   a
4 -1
5 -1
[-1, -1]
Copy after login

The above is the detailed content of How Can I Efficiently Group Consecutive Values in a Pandas DataFrame Column?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template