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

如何从df.hist而非np.hist获取bins的位置?

直接从df.hist获取bins的方法

df.hist()本质是调用matplotlib的绘图能力生成直方图,它返回的是包含子图(Axes对象)的数组。我们可以通过访问这些Axes对象中的直方图容器(Patch对象)来提取bins信息,无需单独提取列数据再调用plt.hist或np.histogram。

实现步骤

  • 调用df.hist()并保存返回的Axes数组
  • 遍历Axes对象,从中提取直方图的柱子(Patch)信息
  • 通过柱子的位置和宽度计算出完整的bins边界

示例代码

import pandas as pd
import numpy as np

# 生成测试数据
index = pd.date_range('7-22-2022', '7-22-2023', freq='min')
df = pd.DataFrame(np.random.randn(len(index)), index=index)

# 绘制直方图并获取Axes对象集合
axes_array = df.hist(bins=50)

# 遍历每个子图提取bins
for ax in axes_array.flatten():
    # 获取当前子图的所有直方图柱子
    patches = ax.patches
    if patches:
        # 收集每个柱子的左边界作为bins的左端点
        bins = [patch.get_x() for patch in patches]
        # 补充最后一个bin的右端点(最后一个柱子左边界+宽度)
        bins.append(patches[-1].get_x() + patches[-1].get_width())
        print(f"列 {ax.get_title()} 的bins:")
        print(bins)

单列数据提取bins

如果只需要某一列的bins,可以直接指定列名绘制直方图后提取:

# 绘制指定列的直方图
ax = df[0].hist(bins=50)
# 获取柱子集合
patches = ax.patches
# 计算bins
bins = [p.get_x() for p in patches]
bins.append(patches[-1].get_x() + patches[-1].get_width())
print(bins)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 19:57:35