import datetime import pandas as pd def generate_figure(user_name): with open('./data/orders.txt','r') as f1: orders = [eval(each.strip()) for each in f1.readlines()] users_order = [user for user in orders if user['username'] == user_name] order_list = [] with open('./data/produts.txt','r') as f2: products = [eval(product.strip()) for product in f2.readlines()] for item in users_order: user_all_orders = {} user_all_orders['month'] = datetime.datetime.strftime(datetime.datetime.strptime(item['create_time'],"%Y-%m-%d_%H:%M:%S"),"%B") user_all_orders['pro_id'] = item['pro_id'] user_all_orders['pro_price'] = ''.join([str(each['pro_current_price']) for each in products if each['pro_id'] == item['pro_id']]) order_list.append(user_all_orders) df_orders = pd.DataFrame(order_list)这段代码中我该怎么写才能让df_orders变成group by month并且显示的是该月份消费的proprice的总和
时间: 2024-03-06 07:49:25 浏览: 135
你可以使用 Pandas 中的 `groupby()` 和 `sum()` 函数来实现按月份分组并计算每月的 `proprice` 总和的操作,具体代码如下:
```python
import datetime
import pandas as pd
def generate_figure(user_name):
with open('./data/orders.txt', 'r') as f1:
orders = [eval(each.strip()) for each in f1.readlines()]
users_order = [user for user in orders if user['username'] == user_name]
order_list = []
with open('./data/produts.txt', 'r') as f2:
products = [eval(product.strip()) for product in f2.readlines()]
for item in users_order:
user_all_orders = {}
user_all_orders['month'] = datetime.datetime.strftime(datetime.datetime.strptime(item['create_time'], "%Y-%m-%d_%H:%M:%S"), "%B")
user_all_orders['pro_id'] = item['pro_id']
user_all_orders['pro_price'] = ''.join([str(each['pro_current_price']) for each in products if each['pro_id'] == item['pro_id']])
order_list.append(user_all_orders)
df_orders = pd.DataFrame(order_list)
df_orders['pro_price'] = pd.to_numeric(df_orders['pro_price'])
df_monthly_spending = df_orders.groupby(['month'])['pro_price'].sum()
return df_monthly_spending
```
在这个代码中,我们首先将 `pro_price` 转换为数字类型,然后使用 `groupby()` 函数按照 `month` 列进行分组,最后使用 `sum()` 函数计算每个月份的 `pro_price` 总和。
阅读全文