
本文介绍了如何使用 Pandas DataFrame 根据条件批量更新多行数据,避免循环操作,提高代码效率。核心思路是利用 map() 函数和 update() 函数,将第二个 DataFrame 转换为映射关系,然后根据第一个 DataFrame 的 Symbol 列进行匹配,批量更新 SecurityID 列。
在数据处理过程中,经常会遇到需要根据一个 DataFrame 的信息,批量更新另一个 DataFrame 中符合特定条件的行。例如,我们有两个 DataFrame,df1 和 df2,其中 df1 包含 Symbol 和 SecurityID 列,df2 包含 Symbol 和对应的 SecurityID。我们需要根据 df2 中的 Symbol 和 SecurityID 的对应关系,更新 df1 中所有 Symbol 相同的行的 SecurityID。
以下是一种高效的方法,无需循环即可实现此目的:
1. 准备数据
首先,创建两个示例 DataFrame:
import pandas as pd
# DataFrame 1
data1 = {'Symbol': ['UGE', 'UGE', 'UGE', 'UGE', 'UGE', 'UGE'],
'SecurityID': [None, None, None, None, None, None]}
df1 = pd.DataFrame(data1)
# DataFrame 2
data2 = {'Symbol': ['UGE'],
'SecurityID': [128901]}
df2 = pd.DataFrame(data2)2. 使用 map() 和 update() 函数
核心代码如下:
df1['SecurityID'].update(df1['Symbol'].map(df2.set_index('Symbol')['SecurityID']))这行代码分两步完成:
3. 验证结果
执行完上述代码后,df1 将被更新,所有 Symbol 为 'UGE' 的行的 SecurityID 都将变为 128901。
print(df1)
输出结果:
Symbol SecurityID 0 UGE 128901.0 1 UGE 128901.0 2 UGE 128901.0 3 UGE 128901.0 4 UGE 128901.0 5 UGE 128901.0
完整代码示例:
import pandas as pd
# DataFrame 1
data1 = {'Symbol': ['UGE', 'UGE', 'UGE', 'UGE', 'UGE', 'UGE'],
'SecurityID': [None, None, None, None, None, None]}
df1 = pd.DataFrame(data1)
# DataFrame 2
data2 = {'Symbol': ['UGE'],
'SecurityID': [128901]}
df2 = pd.DataFrame(data2)
# 更新 df1 的 SecurityID
df1['SecurityID'].update(df1['Symbol'].map(df2.set_index('Symbol')['SecurityID']))
print(df1)注意事项:
总结:
使用 map() 和 update() 函数可以高效地批量更新 Pandas DataFrame 中匹配条件的行,避免了循环操作,提高了代码的执行效率。 这种方法在处理大型数据集时尤为重要。 理解并掌握这种方法,可以提升数据处理的效率和代码的可读性。
以上就是Pandas DataFrame:根据条件批量更新多行数据的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号