按多个列的计数轴分组

2024-06-25 06:50:16 发布

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

以图章、性别和种族为标题, 我想按时间戳计算性别和种族组数。给定性别=M/F种族=A/B/C/D/E。你知道吗

Race=E可能不存在于数据集中,但使用Race E预测数据。 因此,占位符对于值为零很重要。

数据和输出示例如下所示。你知道吗

Time_stamp 12:30, 12:30, 12:30, 12:30, 12:31, 12:31, 12:32,

Gender = M, F, F, F, M, F, M

Race = A, A, B, B, C, A, D

enter code here

enter image description here


Tags: 数据标题示例timestamp时间gender性别
1条回答
网友
1楼 · 发布于 2024-06-25 06:50:16

您需要为此创建两个透视表:

要获得包含Race中所有指定类别的表,需要将Race转换为分类变量:

df["Race"] = pd.Categorical(df.Race, categories=["A", "B", "C", "D", "E"])

性别:

 df_g =  df.groupby(["Time_stamp", "Gender"], observed=False).count().fillna(0).unstack() 

对于比赛:

df_r = (df.groupby(["Time_stamp", "Race"], observed=False)
        .count().fillna(0).reset_index()
        .astype({"Race": str}).pivot_table(index="Time_stamp", columns="Race"))

然后你可以加入他们:

df_report = df_r.join(df_g)  
df_report.columns = df_report.columns.droplevel()

相关问题 更多 >