【问题标题】:How can I dynamically create bins in Python?如何在 Python 中动态创建 bin?
【发布时间】:2018-04-15 12:41:17
【问题描述】:

我有以下 np 数组:

[['ID1', 922.63, 'Product 1'],
['ID1', 1001, 'Product 2'],
['ID1', 800, 'Product 1'],
['ID1', 922.63, 'Product 1'],
['ID1', 1001, 'Product 2'],
['ID2', 800, 'Product 1'],
['ID2', 922.63, 'Product 1'],
['ID2', 1001, 'Product 2'],
['ID3', 800, 'Product 1'],
['ID3', 700.63, 'Product 1'],
['ID3', 1200, 'Product 2'],
['ID3', 850, 'Product 1']]

“第二列”(美元金额)是我关心的。我想构建产品 1 和产品 2 的直方图,但我希望将 bin 的大小调整为 100。我使用的实际数据集有 75K 行,值从 1 美元到 200000 美元不等。我想为这些值自动创建这些“桶”,然后构建一个直方图。

我认为使用 pandas 或 numpy 很容易找到这方面的信息,但我要么是新手,无法理解其他“类似”解决方案,要么就是找不到我要找的东西。看起来应该是直截了当的。

【问题讨论】:

  • 每一行是一个字符串或三个单独的列或值,以空格作为分隔符?
  • 我认为this question 与您要查找的内容非常相似...
  • @ScottBoston 我真的不确定。它以数据框开始,我将其转换为 'dataset = dataset.values';打印(数据集)

标签: python pandas numpy matplotlib


【解决方案1】:

您可以通过将数据转换为pandas.DataFrame 来获得直方图:

a = [['ID1', 922.63, 'Product 1'],
['ID1', 1001, 'Product 2'],
['ID1', 800, 'Product 1'],
['ID1', 922.63, 'Product 1'],
['ID1', 1001, 'Product 2'],
['ID2', 800, 'Product 1'],
['ID2', 922.63, 'Product 1'],
['ID2', 1001, 'Product 2'],
['ID3', 800, 'Product 1'],
['ID3', 700.63, 'Product 1'],
['ID3', 1200, 'Product 2'],
['ID3', 850, 'Product 1']]
q=pd.DataFrame(a,columns=['id','price','product'])
q.hist(column='price',bins=100)

您可以使用 bins 参数指定所需的 bin 数量:

 q.hist(column='price', bins=100)

如果您想按产品对其进行分组,请使用by 参数:

 q.hist(column='price', bins=100,by='product')

【讨论】:

  • column=1 是什么意思?那是引用 1 的索引吗?
  • 我修改了代码给价格栏实名
  • 太棒了,还有一件事,你怎么能把它分开并根据每个产品有两个直方图?
猜你喜欢
  • 2020-11-12
  • 1970-01-01
  • 2012-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-01
  • 2021-08-11
  • 1970-01-01
相关资源
最近更新 更多