python - 根据引用其他 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
推荐阅读
- php - 存储注册状态未正常工作(始终存储值“C”但如果注册已付费则应存储“I”)
- java - 将数组元素乘以 n,并将它们存储在新数组中
- matrix - 大型矩阵乘法大小的恒定输出
- vue.js - 如何将命名插槽插入父组件
- python - 在 Python 协程中更新函数调用
- sql - SQL查询将2个日期列组合成一个组合列
- javascript - 从根组件作为道具传递的对象,不呈现更改
- java - JTable 上的侦听器问题(执行代码太多次)
- android - 回历日历 - com.github.msarhan.ummalqura.calendar.text.UmmalquraFormatData_fr_FR',键''
- java - 休眠会话是否在春季关闭?