【问题标题】:Pandas - map dictionary keys and values to new columnPandas - 将字典键和值映射到新列
【发布时间】:2020-10-04 04:52:22
【问题描述】:

我有一个 df:

Int64Index: 3572 entries
Data columns (total 58 columns): 

带有“团队”列:

 #   Column                        Non-Null Count  Dtype  
---  ------                        --------------  -----  
...
 13  team                         3572 non-null   object 
...

将以下项目作为唯一值,重复多次:

teams = [
    'Grêmio','Internacional', 'Palmeiras', 'Ceará', 
    'Bragantino', 'Corinthians', 'Botafogo', 'Fluminense', 
    'Flamengo', 'Athlético-PR','Coritiba': 'São Paulo',
    'Bahia', 'Sport', 'Fortaleza', 'Atlético-GO',
    'Goiás', 'Santos', 'Atlético-MG', 'Vasco']

现在,根据下面的字典:

next_round = {
    'Grêmio':'Internacional', 'Palmeiras': 'Ceará', 
    'Bragantino': 'Corinthians', 'Botafogo': 'Fluminense', 
    'Flamengo': 'Athlético-PR','Coritiba': 'São Paulo',
    'Bahia': 'Sport', 'Fortaleza': 'Atlético-GO',
    'Goiás': 'Santos', 'Atlético-MG': 'Vasco'}

我想:

  1. 创建一个新列df['home_dummy']
  2. 如果df['team'] 行值是字典key,则将值'home' 分配给df['home_dummy']
  3. 如果df['team] 行值是字典value,则将值“离开”分配给df['home_dummy']

如key, value in next_round.items()

例子:

team            home_dummy /
...
Grêmio          home
Internacional   away
Palmeiras       home
Vasco           away
Coritiba        home
...

pandas 这样做的方式是什么?

【问题讨论】:

  • 您能否提供一个输出示例,以便我们知道您在寻找什么。我不明白什么是关键。查找从哪里来检查键或值。换句话说,您能否提供示例源数据和示例所需的输出。请一份在家,一份在外。
  • @JoeFerndz 键是字典键,如k, v in next_round.items()

标签: python pandas


【解决方案1】:
import pandas as pd

df = pd.DataFrame([['Grêmio'],['Internacional'],['Palmeiras'],['Vasco'],['Coritiba']],columns = ['teams'])
next_round = {
    'Grêmio':'Internacional', 'Palmeiras': 'Ceará', 
    'Bragantino': 'Corinthians', 'Botafogo': 'Fluminense', 
    'Flamengo': 'Athlético-PR','Coritiba': 'São Paulo',
    'Bahia': 'Sport', 'Fortaleza': 'Atlético-GO',
    'Goiás': 'Santos', 'Atlético-MG': 'Vasco'}
df['home_dummy'] = ['home' if x in next_round.keys() else 'away' for x in df['teams'] ]
df

   teams    home_dummy
0   Grêmio  home
1   Internacional   away
2   Palmeiras   home
3   Vasco   away
4   Coritiba    home

【讨论】:

    猜你喜欢
    • 2016-09-02
    • 2023-02-21
    • 2020-09-01
    • 2020-03-23
    • 1970-01-01
    • 2015-07-24
    • 2021-11-25
    • 2021-08-31
    • 2021-06-26
    相关资源
    最近更新 更多