python - 根据引用其他 DataFrame 的值的索引复制列中的值

标签 python python-3.x pandas dataframe

我在根据 df2["index"] 的值创建新列时遇到问题。我想得到的是基于其实际索引的 df1["score"] 中的值。

它让它更容易理解,这是我的两个示例数据框:

df1= pd.DataFrame({'cluster':[1,2,3,4,5], 'score':[80, 90, 60, 40, 12]})  
df2= pd.DataFrame({'word':["hello", "my", "name", "is", "tom"], 'label':["aa", "bb", "cc", "dd", "ee"], 'idx':[1,3,4,4,4]})  

这是我期望的结果,其中根据 df2 的“索引”列和 df1 的“实际索引”引用了分数

df3= pd.DataFrame({'word':["hello", "my", "name", "is", "tom"], 'label':["aa", "bb", "cc", "dd", "ee"], 'idx':[1,3,4,4,4], 'score':[90, 40, 12, 12, 12]})

最佳答案

使用Series.map通过 Series df1['score'] 与索引值匹配:

df2['score'] = df2['idx'].map(df1['score'])
print (df1)
    word label  idx  score
0  hello    aa    1     90
1     my    bb    3     40
2   name    cc    4     12
3     is    dd    4     12
4    tom    ee    4     12

关于python - 根据引用其他 DataFrame 的值的索引复制列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56377027/

相关文章:

python - 如何处理管道中处理相互依赖的文件

python - 如何根据输入年份生成包含一年中各天的数据框?

python - unique_for_date 的用法

python - 简单的 Python 字符串(向后)切片

python - Pandas 映射到多个字典项以对数据进行分类

python - Pandas - 字典列表的列扩展 - 如何优化?

python - Google Colaboratory 将文件保存到 Github 时显示错误 "Could not fetch branches. "

python - 子进程完成但仍未终止,导致死锁

python-3.x - concurrent.futures.Future 可以转换为 asyncio.Future 吗?

python - 加快 pandas 操作速度