python - 根据索引合并两个数据框,替换其他列中的匹配值

标签 python pandas replace

我有以下宽 df1:

Area geotype  type    ...
1      a        2      ...
1      a        1      ... 
2      b        4      ...
4      b        8      ...

以及以下两列 df2:

Area   geotype
1      London
4      Cambridge

我想要以下内容:

Area  geotype  type    ...
1     London     2      ...
1     London     1      ... 
2       b        4      ...
4     Cambridge  8      ...

所以我需要根据非唯一的Area列进行匹配,然后只有匹配到,才替换geotype列中的设置值。

如果这是重复的,我深表歉意,我确实在努力寻找解决方案。

最佳答案

使用更新 + map

df1.geotype.update(df1.Area.map(df2.set_index('Area').geotype))

   Area    geotype  type
0     1     London     2
1     1     London     1
2     2          b     4
3     4  Cambridge     8

关于python - 根据索引合并两个数据框,替换其他列中的匹配值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41750916/

相关文章:

Python 3.4 类型错误 : argument of type 'int' is not iterable

python - 从 Excel 中提取两列并将键值对附加到字典

python - 在python中选择满足跨多列条件的记录

python,帮助替换第一个字母

javascript - 我可以使用正则表达式替换字符串中的所有关键字吗? (Python)

python - 如何比较两个长度、顺序未知且具有重复值的列表中的每个项目,同时最小化写入并保留 Python 中的位置?

python - Google BigQuery 请求太大

python - 将唯一字符串映射到 Python 中的整数

python - 我想使用 matplotlib 从数据框中绘制多个变量,但最终的图看起来很奇怪

c++ - 用另一个字符序列替换 C++ std::string 中的字符/字符序列