Skip to main content
 首页 » 编程设计

python之Pandas 注释数据框历史

2024年10月17日8qq号

df = { 'id' : pd.Series([1,1,1,1,2,2,2,2,3,3,4,4,4])} 
 
num_id = df['id'].value_counts().hist(bins=2) 

我得到了一个很好的直方图,其中包含落入每个容器中的 ID 数量。

问题是,如何为每个条添加注释以显示计数?它可能位于带有白色文本的中间。

我知道我们可以在 hist() 中指定一个 ax 参数,但我不确定如何指定。

请您参考如下方法:

给你(使用 import 语句,以防万一):

import pandas as pd 
import matplotlib.pyplot as plt 
 
df = pd.DataFrame({ 'id' : [1,1,1,1,2,2,2,2,3,3,4,4,4]}) 
 
fig, ax = plt.subplots() 
freq, bins, _ = ax.hist(df['id'].value_counts(), 2, facecolor='skyblue') 
ax.grid(True) 
for i, n in enumerate(freq): 
    ax.text(bins[i]+0.5, 2, n) 
ax.set_xlabel('Bins') 
ax.set_ylabel('Freq') 
plt.show()