我可以在 pandas、python 中包含从 excel 到边索引的多个数据列吗
Can I include multiple data columns from excel to side index in pandas, python
我需要将多选品牌问题中的数据(excel 中的数据作为每个选项的单独列)提取到交叉表 table 的边索引中。我尝试在交叉表的索引参数中传递列表,但它没有提供所需的输出。
如果我能得到一个总专栏也很有帮助。
下面是数据样本和所需的输出格式。
Brand 1
Brand 2
Brand 3
Brand 4
Gender
HP
Acer
Male
Dell
Acer
MSI
Apple
Male
Apple
HP
Asus
Female
HP
Apple
Male
需要的输出:
Brand
Male
Female
Acer
2
0
Apple
2
1
Asus
0
1
Dell
1
0
HP
2
1
MSI
1
0
非常感谢您的努力。
用 nan 和 stack 替换空格后尝试交叉表,然后根据需要重命名轴:
o = pd.crosstab(df.filter(like="Brand").replace('',np.nan).stack().droplevel(1),
df['Gender'])
out = o.rename_axis(index='Brand',columns=None).reset_index()
print(out)
Brand Female Male
0 Acer 0 2
1 Apple 1 2
2 Asus 1 0
3 Dell 0 1
4 HP 1 2
5 MSI 0 1
使用 value_counts 添加另一个备选方案并取消堆叠:
a = df.filter(like='Brand').replace('',np.nan).stack().to_frame('Brands').droplevel(1)
out = (a.join(df['Gender']).groupby("Brands")['Gender'].value_counts()
.unstack(fill_value=0))
我需要将多选品牌问题中的数据(excel 中的数据作为每个选项的单独列)提取到交叉表 table 的边索引中。我尝试在交叉表的索引参数中传递列表,但它没有提供所需的输出。 如果我能得到一个总专栏也很有帮助。
下面是数据样本和所需的输出格式。
Brand 1 | Brand 2 | Brand 3 | Brand 4 | Gender |
---|---|---|---|---|
HP | Acer | Male | ||
Dell | Acer | MSI | Apple | Male |
Apple | HP | Asus | Female | |
HP | Apple | Male |
需要的输出:
Brand | Male | Female |
---|---|---|
Acer | 2 | 0 |
Apple | 2 | 1 |
Asus | 0 | 1 |
Dell | 1 | 0 |
HP | 2 | 1 |
MSI | 1 | 0 |
非常感谢您的努力。
用 nan 和 stack 替换空格后尝试交叉表,然后根据需要重命名轴:
o = pd.crosstab(df.filter(like="Brand").replace('',np.nan).stack().droplevel(1),
df['Gender'])
out = o.rename_axis(index='Brand',columns=None).reset_index()
print(out)
Brand Female Male
0 Acer 0 2
1 Apple 1 2
2 Asus 1 0
3 Dell 0 1
4 HP 1 2
5 MSI 0 1
使用 value_counts 添加另一个备选方案并取消堆叠:
a = df.filter(like='Brand').replace('',np.nan).stack().to_frame('Brands').droplevel(1)
out = (a.join(df['Gender']).groupby("Brands")['Gender'].value_counts()
.unstack(fill_value=0))