
在数据处理中,我们经常遇到这样的场景:需要根据一个或多个列的值,从另一个数据源更新当前dataframe中的数据。当更新条件涉及的列(例如symbol)在目标dataframe中存在多行匹配时,传统的dataframe.update()方法默认基于索引进行更新,可能无法满足需求,而dataframe.merge()则倾向于创建新的dataframe或处理合并逻辑,对于原地更新特定列而言并非最优解。
考虑以下两个DataFrame:
DF1 (目标DataFrame):
import pandas as pd
import numpy as np
df1_data = {
'Symbol': ['UGE', 'UGE', 'UGE', 'UGE', 'UGE', 'UGE'],
'SecurityID': [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]
}
df1 = pd.DataFrame(df1_data, index=[3856, 13583, 25422, 36046, 47362, 58434])
print("DF1:")
print(df1)输出:
Symbol SecurityID 3856 UGE NaN 13583 UGE NaN 25422 UGE NaN 36046 UGE NaN 47362 UGE NaN 58434 UGE NaN
DF2 (源DataFrame):
df2_data = {
'Symbol': ['UGE'],
'SecurityID': [128901]
}
df2 = pd.DataFrame(df2_data, index=[3856])
print("\nDF2:")
print(df2)输出:
Symbol SecurityID 3856 UGE 128901
我们的目标是使用DF2中的SecurityID来更新DF1中所有Symbol为'UGE'的行的SecurityID。
直接使用df1.update(df2)会遇到问题,因为它主要依赖索引进行匹配。由于DF2中只有一个索引为3856的行,因此只有DF1中索引为3856的行会被更新:
df1_copy = df1.copy()
df1_copy.update(df2)
print("\n使用 df1.update(df2) 的结果:")
print(df1_copy)输出:
Symbol SecurityID 3856 UGE 128901 13583 UGE NaN 25422 UGE NaN 36046 UGE NaN 47362 UGE NaN 58434 UGE NaN
可以看到,只有第一行被更新,其他具有相同Symbol的行仍然是NaN。
为了实现基于非索引列的条件更新,我们可以巧妙地结合使用Series.map()和Series.update()方法。
创建映射关系: 首先,将源DataFrame df2转换为一个Series,其索引是用于匹配的列(Symbol),值是需要更新的列(SecurityID)。这实际上创建了一个查找表。
# 创建一个从Symbol到SecurityID的映射Series
symbol_to_securityid_map = df2.set_index('Symbol')['SecurityID']
print("\n映射Series (symbol_to_securityid_map):")
print(symbol_to_securityid_map)输出:
Symbol UGE 128901 Name: SecurityID, dtype: int64
应用映射: 接着,使用df1['Symbol'].map()将这个映射应用到DF1的Symbol列上。map()方法会遍历df1['Symbol']中的每个值,并在symbol_to_securityid_map中查找对应的值。如果找到,则返回对应的值;如果未找到,则返回NaN。这会生成一个新的Series,其索引与df1对齐,值则是根据Symbol匹配到的SecurityID。
# 应用映射到df1的Symbol列,生成待更新的SecurityID Series
mapped_security_ids = df1['Symbol'].map(symbol_to_securityid_map)
print("\n应用映射后的SecurityID Series (mapped_security_ids):")
print(mapped_security_ids)输出:
3856 128901 13583 128901 25422 128901 36046 128901 47362 128901 58434 128901 Name: Symbol, dtype: int64
请注意,mapped_security_ids的索引与df1的索引是完全一致的。
执行更新: 最后,使用df1['SecurityID'].update()方法,将mapped_security_ids中的值更新到df1的SecurityID列中。Series.update()方法会根据索引匹配进行原地更新。由于mapped_security_ids的索引与df1['SecurityID']的索引完全一致,所有匹配的行都将被正确更新。
# 执行原地更新
df1['SecurityID'].update(mapped_security_ids)
print("\n最终更新后的DF1:")
print(df1)输出:
Symbol SecurityID 3856 UGE 128901.0 13583 UGE 128901.0 25422 UGE 128901.0 36046 UGE 128901.0 47362 UGE 128901.0 58434 UGE 128901.0
将上述步骤整合为一行代码:
# 完整解决方案
df1['SecurityID'].update(df1['Symbol'].map(df2.set_index('Symbol')['SecurityID']))结合Series.map()和Series.update()提供了一种优雅且高效的方式来解决Pandas DataFrame中基于非索引列的条件性多行更新问题。通过将源数据转换为一个映射Series,并利用map()进行值查找和update()进行索引对齐的更新,我们能够实现精确且高性能的数据操作,这在处理复杂数据集成和转换任务时尤为实用。
以上就是Pandas DataFrame条件匹配多行更新:高效利用map与update的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号