首页 > 解决方案 > 用另一个数据帧中的值替换熊猫数据帧的多个值的最快方法

问题描述

我正在尝试用来自另一个数据帧的值替换多行熊猫数据帧。

假设我的数据框中有 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 中的值的任何东西都可以。

标签: pythonpython-3.xpandasdataframe

解决方案


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

或者,您可以就地进行。

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

推荐阅读