从直方图创建dict

2024-04-23 06:36:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望从直方图创建一个json/dict。你知道吗

pandas加载数据并绘制它,结果如下

import pandas as pd

df = pd.read_csv(PATH_TO_CSV)
df.hist(log=True)

结果如下: Example histogram

我想知道什么是最好的方式得到这个作为一个dict,我不严格的方式,我希望dict看起来像,但我想像这样的东西

histogram = {
    'dropoff_latitude': {
        '30-35': 1800000,
        .....
    },
    'dropoff_longitude': {
        ....
    }
}

Tags: csv数据pathimportjsonpandasdfread
1条回答
网友
1楼 · 发布于 2024-04-23 06:36:15

这里有一条路。histfuncreates从np.histogram获取箱子和计数信息。并且,label创建bin表示。你知道吗

In [95]: def histfun(x):
    ...:     hist, bins = np.histogram(x)
    ...:     bbins = np.char.mod('%.2f', bins)
    ...:     label = map('-'.join, zip(bbins[:-1], bbins[1:]))
    ...:     return dict(zip(label, hist))
    ...:

In [96]: df.apply(histfun).to_dict()
Out[96]:
{'dropoff_latitude': {'30.00-35.00': 2,
  '35.00-40.00': 0,
  '40.00-45.00': 0,
  '45.00-50.00': 1,
  '50.00-55.00': 0,
  '55.00-60.00': 0,
  '60.00-65.00': 0,
  '65.00-70.00': 0,
  '70.00-75.00': 0,
  '75.00-80.00': 1},
 'dropoff_longitude': {'0.00-12.00': 2,
  '108.00-120.00': 1,
  '12.00-24.00': 0,
  '24.00-36.00': 0,
  '36.00-48.00': 0,
  '48.00-60.00': 0,
  '60.00-72.00': 1,
  '72.00-84.00': 0,
  '84.00-96.00': 0,
  '96.00-108.00': 0}}

样品测试数据

In [97]: df
Out[97]:
   dropoff_latitude  dropoff_longitude
0                30                120
1                30                  0
2                45                  0
3                80                 60

相关问题 更多 >