python - 在 Pandas 中如何引用 2 个数据框并替换列

标签 python pandas

有 2 个数据框: 需要使用“Place”引用表将 df 中的“Region”替换(或添加一列来指示) ref 中的“Code”。 请注意,这是一个示例,在真实文件中,有 100,000 多个角色,以及更复杂的值。请帮忙

df=pd.DataFrame({'Date': ['1/1/11','1/2/11','1/2/11','1/2/11','1/3/11','1/3/11','1/3/11','1/3/11','1/4/11','1/5/11','1/5/11','1/5/11'],\
'Prod': ['Quad','Bellen','Quad','Bellen','Sunshine','Carlota','Sunset','Sunshine','Sunset','Sunset','Sunshine','Carlota'], \
'Region': ['East','South','West','West','East','MidWest','South','South','MidWest','South','West','West']})

ref=pd.DataFrame({'Place': ['West','East','South','MidWest'],\
'Code':['W','E','S','MW']})

最佳答案

您需要 map

df['Region'] = df['Region'].map(ref.set_index('Place')['Code'])


    Date    Prod        Region
0   1/1/11  Quad        E
1   1/2/11  Bellen      S
2   1/2/11  Quad        W
3   1/2/11  Bellen      W
4   1/3/11  Sunshine    E
5   1/3/11  Carlota     MW
6   1/3/11  Sunset      S
7   1/3/11  Sunshine    S
8   1/4/11  Sunset      MW
9   1/5/11  Sunset      S
10  1/5/11  Sunshine    W
11  1/5/11  Carlota     W

编辑:如果您想保留 ref 中不存在的区域名称,请使用

df['Region'] = df['Region'].map(ref.set_index('Place')['Code']).combine_first(df['Region'])

编辑:@Wen 是对的,您可以使用替换而不是 map

df['Region'].replace(ref.set_index('Place')['Code'])

关于python - 在 Pandas 中如何引用 2 个数据框并替换列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49344531/

相关文章:

Python:遍历数据框列,检查存储在数组中的条件值,并将值获取到列表

python - 如何通过继承有效地使用鸭子类型(duck typing)

python - deeplab在自己的数据集上训练时从检查点恢复失败

Python Telegram Bot : Prompt for another input

python - 将模型从一个 Django 应用程序迁移到多个其他应用程序

python - 从日期时间获取日期和小时作为新列

python - 如何获取 Spark DataFrame 中每行列表中最高值的索引? [PySpark]

python - 如何将项目分组到 1-10 的桶中?

python - 迭代特定行中包含字符串的某些列

python - 有没有办法在保留行颜色的同时将行附加到现有的 csv 文件?