Skip to main content
 首页 » 编程设计

python之来自 Pandas DataFrame 的直方图值

2024年10月24日13kuangbin

我想从 DataFrame 中获取直方图值:

%matplotlib inline 
import pandas as pd 
import numpy as np 
 
df=pd.DataFrame(60*np.random.sample((100, 4)), pd.date_range('1/1/2014',periods=100,freq='D'), ['A','B','C','D']) 

考虑到 pd.cut() 可以只用一列来完成,如 example :

bins=np.linspace(0,60,5) 
df.groupby(pd.cut(df.A,bins)).count() 

是否可以在一个 DataFrame 中获取所有列的完整直方图值? 所需的输出如下所示:

            A   B   C   D        
(0, 15]     21  10  1   2 
(15, 30]    14  24  21  24 
(30, 45]    10  0   22  30 
(45, 60]    25  5   25  25 

请您参考如下方法:

这个技术怎么样,本质上是列表理解和 pd.concat()

np.random.seed(1)     
bins=np.linspace(0,60,5) 
df=  pd.concat([df[x].groupby(pd.cut(df[x],bins)).count() for x in df.columns],axis=1) 
df.index.names = [None] 
print df 

对我来说产生:

           A   B   C   D 
 
(0, 15]   26  20  31  23 
(15, 30]  23  23  20  18 
(30, 45]  24  32  24  29 
(45, 60]  27  25  25  30