英文:
Pandas transform table to occurrence
问题
把表格转化为如下所示:
Fruits and Region Good Bad N/A
0 Apple America 1.0 0.0 0.0
1 Apple Europe 0.0 0.0 1.0
2 Apple Asia 0.0 1.0 0.0
3 Orange America 0.0 0.0 1.0
4 Orange Europe 0.0 1.0 0.0
5 Orange Asia 1.0 0.0 0.0
你可以尝试使用 Pandas 库中的 melt
函数来实现这种转换。
英文:
Hi I have a table similar to below
Fruits America Europe Asia
0 Apple Good N/A Bad
1 Orange N/A Bad Good
and I would like to transform into something like this
Fruits and Region Good Bad N/A
0 Apple America 1 0 0
1 Apple Europe. 0. 0. 1
2 Apple Asia. 0 1. 0
3 Orange America. 0. 0. 1
4 Orange Europe. 0. 1. 0
5 Orange Asia. 1. 0. 0
I have tried the stack function but it doesn't work as expected.
Thank you
答案1
得分: 1
以下是翻译好的部分:
df2 = df.melt('Fruits', var_name='Region')
out = (
pd.crosstab(df2['Fruits'].add(' '+df2['Region']).rename('Fruits and Region'),
df2['value'].fillna('N/A'), dropna=False)
.rename_axis(columns=None).reset_index()
)
输出:
Fruits and Region Bad Good N/A
0 Apple America 0 1 0
1 Apple Asia 1 0 0
2 Apple Europe 0 0 1
3 Orange America 0 0 1
4 Orange Asia 0 1 0
5 Orange Europe 1 0 0
英文:
df2 = df.melt('Fruits', var_name='Region')
out = (
pd.crosstab(df2['Fruits'].add(' '+df2['Region']).rename('Fruits and Region'),
df2['value'].fillna('N/A'), dropna=False)
.rename_axis(columns=None).reset_index()
)
Output:
Fruits and Region Bad Good N/A
0 Apple America 0 1 0
1 Apple Asia 1 0 0
2 Apple Europe 0 0 1
3 Orange America 0 0 1
4 Orange Asia 0 1 0
5 Orange Europe 1 0 0
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论