使用字典键/值重新映射数据框值

时间:2020-10-09 04:14:32

标签: python-3.x pandas dataframe dictionary

我有一个模拟球队得分字典:

{'t1': 83,
 't2': 82,
 't3': 66,
 't4': 74}

以及对战数据框:

team_home  score_home  team_away  score_away
t1         0           t2         0
t3         0           t4         0

我想用字典中相应团队的分数重新映射数据框中的分数。最终输出应如下所示:

team_home  score_home  team_away  score_away
t1         83           t2        82
t3         66           t4        74

2 个答案:

答案 0 :(得分:4)

filter之类的team列,然后stack重塑形状,map dct中的值,然后使用unstack并分配结果到对应的score之类的列:

c = df.filter(like='team').columns
df['score' + c.str.lstrip('team')] = df[c].stack().map(dct).unstack()

  team_home  score_home team_away  score_away
0        t1          83        t2          82
1        t3          66        t4          74

答案 1 :(得分:0)

考虑事先提供以下代码的情况。

import pandas as pd

df = pd.DataFrame({
    'team_home': ['t1', 't3'],
    'score_home': [0, 0],
    'team_away': ['t2', 't4'],
    'score_away': [0, 0],
})
print(df)
#   team_home  score_home team_away  score_away
# 0        t1           0        t2           0
# 1        t3           0        t4           0

team_scores = {
    't1': 83,
    't2': 82,
    't3': 66,
    't4': 74
}
print(team_scores)
# {'t1': 83, 't2': 82, 't3': 66, 't4': 74}

使用熊猫.replace()。解决方法如下。

# Divide into home and away.
df_home = df[['team_home', 'score_home']]
df_away = df[['team_away', 'score_away']]

# Find all the keys in team_scores and replace with that value.
df_home_all = pd.DataFrame()
df_away_all = pd.DataFrame()
for key in team_scores.keys():
    df_home1 = df_home[df_home['team_home'] == key].copy()
    df_home1['score_home'] = df_home1['score_home'].replace(0, team_scores[key])
    df_away1 = df_away[df_away['team_away'] == key].copy()
    df_away1['score_away'] = df_away1['score_away'].replace(0, team_scores[key])
    df_home_all = pd.concat([df_home_all, df_home1], axis=0)
    df_away_all = pd.concat([df_away_all, df_away1], axis=0)

# Finally concat.
output = pd.concat([df_home_all, df_away_all], axis=1)
print(output)
#   team_home  score_home team_away  score_away
# 0        t1          83        t2          82
# 1        t3          66        t4          74