Skip to main content
 首页 » 编程设计

python之用另一个数据帧的值替换 Pandas 数据帧的多个值的最快方法

2025年05月04日15kevingrace

我正在尝试用另一个数据框中的值替换多行 pandas 数据框。

假设我的数据框 df1 中有 10,000 行 customer_id,我想用 df2 中的 3,000 个值替换这些 customer_id。

为了便于说明,让我们生成数据帧(如下)。

假设 df1 中的这 10 行代表 10,000 行,df2 中的 3 行代表 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']) 

我想把180换成1800,把110换成1100,把150换成1500。

我知道我们可以在下面做...

# Replace multiple values 
replace_values = {180 : 1800, 110 : 1100, 150 : 1500 }                                                                                           
df1_replaced = df1.replace({'customer_id': replace_values}) 

如果我只有几行,它工作正常......

但是如果我有数千行需要替换,我怎么能在不输入我想要一次更改的值的情况下执行此操作呢?

编辑:澄清一下,我不需要使用replace。任何可以以最快最有效的方式从 df2 中的值替换 df1 中的那些值的任何东西都是可以的。

请您参考如下方法:

df1['customer_id'] = df1['customer_id'].replace(df2['customer_id_new']) 

或者,您可以就地进行。

df1['customer_id'].replace(df2['customer_id_new'], inplace=True)