将Pandas表转换为出现次数

huangapple go评论75阅读模式
英文:

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

以下是翻译好的部分:

你可以使用 meltcrosstab 函数:

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
英文:

You can melt and crosstab:

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

huangapple
  • 本文由 发表于 2023年3月7日 00:43:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75653530.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定