将Pandas表转换为出现次数

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

Pandas transform table to occurrence

问题

把表格转化为如下所示:

  1. Fruits and Region Good Bad N/A
  2. 0 Apple America 1.0 0.0 0.0
  3. 1 Apple Europe 0.0 0.0 1.0
  4. 2 Apple Asia 0.0 1.0 0.0
  5. 3 Orange America 0.0 0.0 1.0
  6. 4 Orange Europe 0.0 1.0 0.0
  7. 5 Orange Asia 1.0 0.0 0.0

你可以尝试使用 Pandas 库中的 melt 函数来实现这种转换。

英文:

Hi I have a table similar to below

  1. Fruits America Europe Asia
  2. 0 Apple Good N/A Bad
  3. 1 Orange N/A Bad Good

and I would like to transform into something like this

  1. Fruits and Region Good Bad N/A
  2. 0 Apple America 1 0 0
  3. 1 Apple Europe. 0. 0. 1
  4. 2 Apple Asia. 0 1. 0
  5. 3 Orange America. 0. 0. 1
  6. 4 Orange Europe. 0. 1. 0
  7. 5 Orange Asia. 1. 0. 0

I have tried the stack function but it doesn't work as expected.

Thank you

答案1

得分: 1

以下是翻译好的部分:

你可以使用 meltcrosstab 函数:

  1. df2 = df.melt('Fruits', var_name='Region')
  2. out = (
  3. pd.crosstab(df2['Fruits'].add(' '+df2['Region']).rename('Fruits and Region'),
  4. df2['value'].fillna('N/A'), dropna=False)
  5. .rename_axis(columns=None).reset_index()
  6. )

输出:

  1. Fruits and Region Bad Good N/A
  2. 0 Apple America 0 1 0
  3. 1 Apple Asia 1 0 0
  4. 2 Apple Europe 0 0 1
  5. 3 Orange America 0 0 1
  6. 4 Orange Asia 0 1 0
  7. 5 Orange Europe 1 0 0
英文:

You can melt and crosstab:

  1. df2 = df.melt('Fruits', var_name='Region')
  2. out = (
  3. pd.crosstab(df2['Fruits'].add(' '+df2['Region']).rename('Fruits and Region'),
  4. df2['value'].fillna('N/A'), dropna=False)
  5. .rename_axis(columns=None).reset_index()
  6. )

Output:

  1. Fruits and Region Bad Good N/A
  2. 0 Apple America 0 1 0
  3. 1 Apple Asia 1 0 0
  4. 2 Apple Europe 0 0 1
  5. 3 Orange America 0 0 1
  6. 4 Orange Asia 0 1 0
  7. 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:

确定