You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于30分钟时间区间的资金流向柱状图绘制报错求助

解决Pandas按时间分组绘图的TypeError问题

问题根源

  1. date列是字符串格式,未转换为datetime类型,导致设置为索引后不是DatetimeIndex,无法使用pd.Grouper(freq='30Min')进行时间分组。
  2. 原聚合逻辑未区分inflow和outflow的净额,直接求和无法体现资金流向的净结果。

修正后的完整代码

import pandas as pd
import matplotlib.pyplot as plt

# 假设你的DataFrame已加载为df
# 1. 将date列转换为datetime类型
df['date'] = pd.to_datetime(df['date'])

# 2. 清理dollar列,去掉逗号并转为数值类型
df['dollar'] = df['dollar'].str.replace(',', '').astype(float)

# 3. 根据flow计算净额:inflow为正,outflow为负
df['net_dollar'] = df.apply(lambda row: row['dollar'] if row['flow'] == 'inflow' else -row['dollar'], axis=1)

# 4. 按30分钟时间块分组,求净额总和
grouped = df.groupby(pd.Grouper(key='date', freq='30Min'))
aggregated = grouped['net_dollar'].sum().reset_index()

# 5. 确定每个时间块的柱子颜色:净额为负(净流出)用红色,正(净流入)用绿色
aggregated['color'] = aggregated['net_dollar'].apply(lambda x: 'red' if x < 0 else 'green')

# 6. 绘制柱状图
plt.figure(figsize=(10,6))
plt.bar(aggregated['date'], aggregated['net_dollar'], color=aggregated['color'])
plt.xlabel('30-Minute Time Block')
plt.ylabel('Net Dollar Amount')
plt.title('Net Dollar Flow by 30-Minute Intervals')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

关键修正点说明

  • 先通过pd.to_datetime()将date列转为datetime类型,确保时间分组逻辑正常运行。
  • 处理dollar列格式,去除千分位逗号并转为数值,避免求和时因字符串类型报错。
  • 新增net_dollar字段,给outflow金额设置负值,分组求和后直接得到对应时间块的净流量。
  • 基于净流量正负判断柱子颜色,准确反映资金的净流向。

内容的提问来源于stack exchange,提问作者Fffffff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 01:37:11