如何在 Python 中自定义此 DataFrame 上完成的此 .groupby 操作的输出?

How can I customize the output of this .groupby operation done on this DataFrame in Python?

我正在使用 DataFrame 通过计算一列中的三种类型的值来创建频率分布。在这个例子中,我计算并显示每个人的“个人状态”。当我执行代码时,所有其他列都显示在每列中重复的计数。我希望每个值的计数在没有列标题的情况下显示一次。我需要做什么才能做到这一点?

creditData.groupby(['Personal_Status']).count()

这是我的输出图像: Current Output

编辑:这是我希望输出的样子:Desired Output

这可能会成功:

(
    creditData[["Age", "Personal_Status"]]
    .groupby(["Personal_Status"]).count()
    .rename({"Age": ""}, axis="columns"
)

您可以创建一个没有名称的新列(此处为空字符串),然后 select 那个并将结果重新制作成您想要的框架。

creditData[''] = 1
creditData.groupby(['Personal_Status']).count()[''].to_frame()

我认为 creditData["Personal_Status"].value_counts() 是最好的解决方案

文档中推荐的是使用Named aggregation

import pandas as pd
animals = pd.DataFrame(
     {
         "kind": ["cat", "dog", "cat", "dog"],
         "height": [9.1, 6.0, 9.5, 34.0],
         "weight": [7.9, 7.5, 9.9, 198.0],
     }
 )

animals.groupby('kind').agg(**{
    '':('height','count')
})

这会让你

kind    
cat 2
dog 2

供参考https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html(搜索命名聚合)