如何使用 pandas cut 绘制直方图
How to draw a histogram using pandas cut
这是我的数据:
df = pd.DataFrame(myList, index=None, columns=['seconds'])
df['count']= pd.cut(df['seconds'], bins = 30)
Categories (30, interval[float64]): [(0.0871, 0.117] < (0.117, 0.145] < (0.145, 0.174] <
(0.174, 0.202] ... (0.83, 0.858] < (0.858, 0.887] <
(0.887, 0.915] < (0.915, 0.944]]
如何根据这个结果绘制直方图? (x轴是浮动值,y是每个桶中值的总数?)我看到很多帖子使用“kind=bar”来绘制但我想知道是否可以通过以下方式绘制这些数据使用直方图 ?
谢谢大家
这是一个简单的例子...希望对您有所帮助:
import random
df = pd.DataFrame([random.randint(1,1000) for i in range(0,100)], columns=['sec'])
df['bin']=pd.cut(df['sec'], bins = 30).astype(str)
df2 = df.groupby('bin').bin.count()
# Fixed to show distribution of bin
df2.plot(kind='bar')
输出:
df2.plot(kind='hist')
bin 直方图的输出在这里:
秒的直方图输出:
df.sec.plot(kind='hist')
使用库 seaborn
的 countplot
函数的答案,在使用 pandas.cut
函数后:
import numpy as np
import pandas as pd
import seaborn as sns
bins = list(range(0, 110, 10))
bins.append(float('inf'))
np.random.seed(31415)
data_age = np.random.randint(low=0, high=120, size=200)
df_test = pd.DataFrame({'age': data_age,
'age_group': pd.cut(data_age, bins=bins, right=False)})
ax = sns.countplot(data=df_test, x='age_group')
ax.tick_params(axis='x', labelrotation=90)
这构建了这种图像:
库版本:
- 麻木:1.18.0
- Pandas: 1.1.5
- Seaborn:0.11.0
这是我的数据:
df = pd.DataFrame(myList, index=None, columns=['seconds'])
df['count']= pd.cut(df['seconds'], bins = 30)
Categories (30, interval[float64]): [(0.0871, 0.117] < (0.117, 0.145] < (0.145, 0.174] <
(0.174, 0.202] ... (0.83, 0.858] < (0.858, 0.887] <
(0.887, 0.915] < (0.915, 0.944]]
如何根据这个结果绘制直方图? (x轴是浮动值,y是每个桶中值的总数?)我看到很多帖子使用“kind=bar”来绘制但我想知道是否可以通过以下方式绘制这些数据使用直方图 ?
谢谢大家
这是一个简单的例子...希望对您有所帮助:
import random
df = pd.DataFrame([random.randint(1,1000) for i in range(0,100)], columns=['sec'])
df['bin']=pd.cut(df['sec'], bins = 30).astype(str)
df2 = df.groupby('bin').bin.count()
# Fixed to show distribution of bin
df2.plot(kind='bar')
输出:
df2.plot(kind='hist')
bin 直方图的输出在这里:
秒的直方图输出:
df.sec.plot(kind='hist')
使用库 seaborn
的 countplot
函数的答案,在使用 pandas.cut
函数后:
import numpy as np
import pandas as pd
import seaborn as sns
bins = list(range(0, 110, 10))
bins.append(float('inf'))
np.random.seed(31415)
data_age = np.random.randint(low=0, high=120, size=200)
df_test = pd.DataFrame({'age': data_age,
'age_group': pd.cut(data_age, bins=bins, right=False)})
ax = sns.countplot(data=df_test, x='age_group')
ax.tick_params(axis='x', labelrotation=90)
这构建了这种图像:
库版本:
- 麻木:1.18.0
- Pandas: 1.1.5
- Seaborn:0.11.0