Home >Backend Development >Python Tutorial >How Can I Perform Aggregation in Pandas?

How Can I Perform Aggregation in Pandas?

Linda Hamilton
Linda HamiltonOriginal
2024-12-05 11:49:15916browse

How Can I Perform Aggregation in Pandas?

Aggregation in Pandas

How can I perform aggregation with Pandas?

Aggregation functions reduce the dimensionality of returned objects. Some common aggregation functions include mean(), sum(), size(), count(), std(), var(), and sem().

df1 = df.groupby(['A', 'B'], as_index=False)['C'].sum()

No DataFrame after aggregation! What happened?

If you group by two or more columns, you may need to specify as_index=False or use Series.reset_index() to convert a MultiIndex Series to columns.

How can I aggregate mainly strings columns (to lists, tuples, strings with separator)?

To aggregate string columns:

df1 = df.groupby('A')['B'].agg(list).reset_index()

For strings with a separator:

df2 = df.groupby('A')['B'].agg(','.join).reset_index()

How can I aggregate counts?

Use GroupBy.size or GroupBy.count.

df1 = df.groupby('A').size().reset_index(name='COUNT')

How can I create a new column filled by aggregated values?

Use GroupBy.transform.

df['C1'] = df.groupby('A')['C'].transform('sum')

The above is the detailed content of How Can I Perform Aggregation in Pandas?. 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