python - 当索引和列不匹配时,如何使用来自另一个数据帧的值更新数据帧
问题描述
如果某些条件成立,我想df
用来自另一个数据帧的值更新数据帧。df_new
数据框的索引和列名不匹配。怎么可能做到?
names = ['a', 'b', 'c']
df = pd.DataFrame({
'val': [10, 10, 10],
}, index=names)
new_names = ['a', 'c', 'd']
df_new = pd.DataFrame({
'profile': [5, 15, 22],
}, index=new_names)
above_max = df_new['profile'] >= 7
# This works only if indexes of df and df_new match
#df.loc[above_max, 'val'] = df_new['profile']
# expected df:
# val
# a 10
# b 10
# c 15
解决方案
Series.reindex
将掩码的索引值与另一个 DataFrame 匹配的一个想法:
s = df_new['profile'].reindex(df.index)
above_max = s >= 7
df.loc[above_max, 'val'] = s
推荐阅读
- javascript - 如何在 Vue.js 中获得假值或真值的总和
- python - 找不到scapy模块
- swift - settingsChangedNotification 仅在 Preferences.app 打开时发送(Swift - OSX)
- pentaho - Pentaho/PDI/Kettle:如何用 Excel 电子表格中的值填充“插入/更新”?
- python - 通过从 pandas 和 scikit-learn 中的非缺失值估计方程来估算缺失值
- rust - 尝试在 JNI 中创建字符串并将其添加到 Arraylist
- php - 上传时ffmpeg水印视频
- c# - CS7069:对类型“Route”的引用声称它在 System.Web 中定义,但找不到
- google-chrome-extension - 从下载事件中获取标签 ID
- flutter - 控制 Flutter swiper 的分页