pandas-柱变量的小区分布

2024-05-19 18:41:44 发布

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

我试着将一些数据可视化,但是我对这个主题没有太多的经验,也很难找到最好的海湾来得到我想要的东西。我四处寻找,发现了类似的问题,但没有什么能确切地回答我想要的,所以希望我不会重复一个常见的问题。

无论如何,我有一个数据框,其中有一列用于patient_id(和其他列,但这是相关的)。例如:

   patient_id  other_stuff
0      000001          ...
1      000001          ...
2      000001          ...
3      000002          ...
4      000003          ...
5      000003          ...
6      000004          ...
etc

其中每一行代表患者发生的特定事件。我想画出x轴是病人发作次数的分布图,y轴是病人发作次数的分布图。例如,基于上述情况,有一个病人有三个发作,一个病人有两个发作,还有两个病人各有一个发作,即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()

这个方法做了我想做的,但我觉得有点不透明,很难遵循,所以我想知道是否有更好的方法。


Tags: ofthe数据idnumbervaluecount分布图
1条回答
网友
1楼 · 发布于 2024-05-19 18:41:44

你可能在找

df.procedure_id.groupby(df.patient_id).nunique().hist();

说明:

  • 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');

enter image description here

相关问题 更多 >