python - 用另一个数据帧中的值替换熊猫数据帧的多个值的最快方法
问题描述
我正在尝试用来自另一个数据帧的值替换多行熊猫数据帧。
假设我的数据框中有 10,000 行 customer_id,df1
我想用 3,000 个值替换这些 customer_id df2
。
为了便于说明,让我们生成数据帧(如下)。
假设这 10 行df1
表示 10,000 行,而 3 行df2
表示 3,000 个值。
import numpy as np
import pandas as pd
np.random.seed(42)
# Create df1 with unique values
arr1 = np.arange(100,200,10)
np.random.shuffle(arr1)
df1 = pd.DataFrame(data=arr1,
columns=['customer_id'])
# Create df2 for new unique_values
df2 = pd.DataFrame(data = [1800, 1100, 1500],
index = [180, 110, 150], # this is customer_id column on df1
columns = ['customer_id_new'])
我想用 1800 替换 180,用 1100 替换 110,用 1500 替换 150。
我知道我们可以在下面做......
# Replace multiple values
replace_values = {180 : 1800, 110 : 1100, 150 : 1500 }
df1_replaced = df1.replace({'customer_id': replace_values})
如果我只有几行,它就可以正常工作......
但是,如果我有数千行需要替换,我怎么能在不输入我想一次更改的值的情况下做到这一点呢?
编辑:澄清一下,我不需要使用replace
. 任何可以以最快最有效的方式将 df1 中的值替换为 df2 中的值的任何东西都可以。
解决方案
df1['customer_id'] = df1['customer_id'].replace(df2['customer_id_new'])
或者,您可以就地进行。
df1['customer_id'].replace(df2['customer_id_new'], inplace=True)
推荐阅读
- node.js - 使用nodejs在mongo中使用对象子过滤
- excel - Excel中连续事件组的交替颜色
- e2e-testing - 每次在数组中搜索不同的值
- vb.net - 使用 DotNetZip 设置 zip 文件的密码
- solidity - 如何可靠地返回地址数组?
- com - TComInterface 没有调用 Release
- azure-devops - Azure Pipelines GitHub 应用程序 - 本地安装?
- sql-server - 如何动态改变一行?
- qt - 哪一种是为以下代码实现 Switch Case 的好方法?
- python - 如何使用 Python Mock 副作用根据被模拟的函数返回不同的值