pandas - 列变量的绘图分布

Wmb*_*uch 5 python visualization pandas

我正在尝试可视化一些数据,但我对这个主题不是很有经验,并且很难找到最佳的海湾来获得我正在寻找的东西。我四处搜索并发现了类似的问题,但没有什么能准确回答我想要的问题,所以希望我没有重复常见问题。

无论如何,我有一个 DataFrame,其中有一列patient_id( 和其他列,但这是相关的。例如:

   patient_id  other_stuff
0      000001          ...
1      000001          ...
2      000001          ...
3      000002          ...
4      000003          ...
5      000003          ...
6      000004          ...
etc
Run Code Online (Sandbox Code Playgroud)

每行代表患者的一个特定发作。我想绘制分布图,其中 x 轴是患者的发作次数,y 轴是发生所述发作次数的患者数量。例如,根据上述情况,有 1 名患者发作 3 次,1 名患者发作 2 次,2 名患者各发作 1 次,即x = [1, 2, 3], y = [2, 1, 1]。目前,我执行以下操作:

episode_count_distribution = (
    patients.patient_id
    .value_counts() # the number of rows for each patient_id (i.e. episodes per patient)
    .value_counts() # the number of patients for each possible row count above (i.e. distribution of episodes per patient)
    .sort_index()
)
episode_count_distribution.plot()
Run Code Online (Sandbox Code Playgroud)

这种方法满足了我的要求,但让我觉得有点不透明且难以遵循,所以我想知道是否有更好的方法。

Ami*_*ory 5

您可能正在寻找类似的东西

df.procedure_id.groupby(df.patient_id).nunique().hist();
Run Code Online (Sandbox Code Playgroud)

解释:

  • df.procedure_id.groupby(df.patient_id).nunique()查找每个患者的独特手术数量。

  • hist()绘制直方图。

例子

df = pd.DataFrame({'procedure_id': [3, 2, 3, 2, 4, 1, 2, 3], 'patient_id': [1, 2, 3, 2, 1, 2, 3, 2]})
df.procedure_id.groupby(df.patient_id).nunique().hist();
xlabel('num patients');
ylabel('num treatments');
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述