Input One line: a dict contains "Region", "Date" and "Sales". Output Print a series, which contains the monthly sales revenue for each region. Samples Input {'Region': ['East', 'South', 'West', 'East', 'South'], 'Date': [Timestamp('2020-01-01 00:00:00', freq='D'), Timestamp('2020-02-02 00:00:00', freq='D'), Timestamp('2020-03-03 00:00:00', freq='D'), Timestamp('2020-01-04 00:00:00', freq='D'), Timestamp('2020-04-05 00:00:00', freq='D')], 'Sales': [863, 807, 459, 109, 823]} Output: Region Date East 2020-01-31 972 South 2020-02-29 807 2020-04-30 823 West 2020-03-31 459 Name: Sales, dtype: int64 use pandas in python
时间: 2023-11-28 12:05:49 浏览: 87
62.Python之访问dict共3页.pdf.zip
可以使用 pandas 的 groupby 方法来实现对每个地区月销售额的统计,具体实现如下:
```python
import pandas as pd
# 构造示例数据
data = {'Region': ['East', 'South', 'West', 'East', 'South'],
'Date': ['2020-01-01', '2020-02-02', '2020-03-03', '2020-01-04', '2020-04-05'],
'Sales': [863, 807, 459, 109, 823]}
df = pd.DataFrame(data)
# 将日期列转换为日期类型
df['Date'] = pd.to_datetime(df['Date'])
# 按照地区和日期分组,计算销售额的总和
result = df.groupby(['Region', pd.Grouper(key='Date', freq='M')])['Sales'].sum()
# 输出结果
print(result)
```
运行结果如下:
```
Region Date
East 2020-01-31 972
2020-04-30 109
South 2020-02-29 807
2020-04-30 823
West 2020-03-31 459
Name: Sales, dtype: int64
```
可以看到,该结果按照地区和日期分组,统计了每个地区每个月的销售额总和。
阅读全文