pythonbook/实验 Pandas_速查表/groupby.py

16 lines
836 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import pandas as pd
import plotly.express as px
data = {
'Date': ['2024-01-01', '2024-01-01', '2024-01-02', '2024-01-02', '2024-01-03', '2024-01-03'],
'Product': ['A', 'B', 'A', 'B', 'A', 'B'],
'Sales': [100, 150, 120, 110, 130, 120]
}
df = pd.DataFrame(data)
grouped_df = df.groupby('Product')['Sales'].sum()
print(grouped_df)
# 这个操作将按照Product列进行分组并计算每个分组中Sales列的总和从而得到每个产品的总销售额。
# 这意味着产品A的总销售额为350而产品B的总销售额为380。通过使用groupby方法我们能够轻松地按照Product列对数据进行分组并计算每个分组的Sales列总和从而得到每个产品在所有日期上的总销售额。这个例子展示了groupby方法在数据分析和处理中的强大功能和灵活性