深度阅读

How to Use the Pandas DataFrame Groupby Method

作者
作者
2023年08月22日
更新时间
11.24 分钟
阅读时间
0
阅读量

To use the Pandas DataFrame groupby method, you can call the groupby() method on a DataFrame and specify the column or columns that you want to group by. Here’s an example:

import pandas as pd

# Create a dataframe
df = pd.DataFrame({
    'fruit': ['apple', 'banana', 'orange', 'apple', 'banana', 'orange'],
    'quantity': [2, 3, 1, 4, 5, 2]
})

# Group the dataframe by the 'fruit' column
grouped = df.groupby('fruit')

# Compute the sum of each fruit's quantity
summed = grouped['quantity'].sum()

# Print the result
print(summed)

In this example, we create a DataFrame with two columns: fruit and quantity. We then use the groupby() method to group the DataFrame by the fruit column. This creates a groupby object that we can use to compute various aggregates.

In this case, we want to compute the sum of each fruit’s quantity. To do this, we select the quantity column from the groupby object and call the sum() method. This computes the sum of each group’s values and returns a new DataFrame.

Finally, we print the result, which is a DataFrame with the sum of each fruit’s quantity.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。