Home > Backend Development > Python Tutorial > How to Efficiently Join Grouped Values in Pandas with a Delimiter?

How to Efficiently Join Grouped Values in Pandas with a Delimiter?

Barbara Streisand
Release: 2024-12-16 19:55:18
Original
344 people have browsed it

How to Efficiently Join Grouped Values in Pandas with a Delimiter?

Joining Grouped Values with a Delimiter in Pandas

When using the groupby function to group data with multiple values, it's common to encounter the issue of concatenating these values without a delimiter. To resolve this, you can leverage the agg method.

Consider the following DataFrame:

col | val
-----|-----
A    | Cat
A    | Tiger
B    | Ball
B    | Bat
Copy after login

To group these rows based on the col column and concatenate the values in the val column, use the following code:

import pandas as pd
df = pd.DataFrame({'col': ['A', 'A', 'B', 'B'], 'val': ['Cat', 'Tiger', 'Ball', 'Bat']})
grouped = df.groupby('col')['val'].agg('-'.join)
Copy after login

This approach should yield the desired result:

col | val
-----|-----
A    | Cat-Tiger
B    | Ball-Bat
Copy after login

However, if the apply method is used as an alternative, it can lead to an unexpected outcome with hyphenated values occurring multiple times, as seen below:

df.groupby('col')['val'].apply(lambda x: '-'.join(x))

col | val
-----|-----
A        | C-a-t-T-i-g-e-r
B          | B-a-l-l-B-a-t
Copy after login

To avoid this issue, use the agg method instead, as demonstrated in the example above.

Additionally, to convert the grouped index or MultiIndex to regular columns, you can use the reset_index method:

df1 = grouped.reset_index(name='new')
Copy after login

The above is the detailed content of How to Efficiently Join Grouped Values in Pandas with a Delimiter?. 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