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

How Can I Perform Aggregation in Pandas?

Linda Hamilton
Release: 2024-12-05 11:49:15
Original
915 people have browsed it

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()
Copy after login

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()
Copy after login

For strings with a separator:

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

How can I aggregate counts?

Use GroupBy.size or GroupBy.count.

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

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

Use GroupBy.transform.

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

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!

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