Home  >  Article  >  Backend Development  >  How to Combine Strings Within Groups Using Pandas groupby?

How to Combine Strings Within Groups Using Pandas groupby?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-24 19:06:29952browse

How to Combine Strings Within Groups Using Pandas groupby?

Pandas groupby: How to get a union of strings

The provided DataFrame contains three columns: A, B, and C. The goal is to group the DataFrame by column A and obtain a union of strings from column C for each group.

By default, groupby sums numeric columns, which doesn't work for strings.

Using a Custom Function

One approach is to define a function that concatenates strings within each group using the join method:

<code class="python">def f(x):
    return "{%s}" % ', '.join(x)</code>

And apply this function to the grouped DataFrame:

<code class="python">result = df.groupby('A')['C'].apply(f)</code>

This approach produces the desired output:

A
1    {This, string}
2           {is, !}
3               {a}
4          {random}

Using sum and Concatenation

Another option is to force sum to concatenate strings by modifying the data type:

<code class="python">df['C'] = df['C'].astype(str)
result = df.groupby('A')['C'].sum()</code>

This also gives the desired result.

The above is the detailed content of How to Combine Strings Within Groups Using Pandas groupby?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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