简体   繁体   English

根据其他数据框替换熊猫数据框中的值

[英]Replace values in pandas dataframe based on other dataframe

I have two dataframes, one in the form of: 我有两个数据框,其中一个的形式为:

#   X   Y   
1   2   0.0 
2   5   0.0 
3   10  0.0 
4   15  0.0 
5   17  0.0 
6   21  0.0 

and one in the form of: 一种形式为:

A   B   C   
1   4   2   
2   5   3   
3   6   4   

I want to replace all the ABC values from the second dataframe, with the X values; 我想用X值替换第二个数据帧中的所有ABC值; so I want go over the ABC df and if the number matches the # of df1 to replace it with the X value 所以我想遍历ABC df,如果该数字与df1的#匹配,则将其替换为X值

the end table should look: 茶几应该看起来像:

A   B   C   
2   15  5   
5   17  10  
10  21  15   

is there a way I can do it? 有办法吗?

IIUC replace IIUC replace

df1.replace(df.set_index('#').X)
Out[382]: 
    A   B   C
0   2  15   5
1   5  17  10
2  10  21  15

say your first DataFrame is a and your second is b , you can map b columns to ax values like this: 假设您的第一个DataFrame是a ,第二个是b ,您可以将b列映射到ax值,如下所示:

b.apply(lambda y: a.x[(y -1).tolist()].values)

The result is: 结果是:

    A   B   C
0   2  15   5
1   5  17  10
2  10  21  15

Only you should use: 只有您应该使用:

df1.set_index('#',inplace = True)
df=df.apply(lambda x: x.replace(df1.loc[x,'X']))

Example: 例:

import pandas as pd
import numpy as np
df1=pd.DataFrame()
df1['#']=[1,2,3,4,5,6]
df1['X']=[2,5,10,15,17,21]
df1['Y']=[0,0,0,0,0,0]
df=pd.DataFrame()
df['A']=[1,2,3]
df['B']=[4,5,6]
df['C']=[2,3,4]
df1.set_index('#',inplace = True)
df=df.apply(lambda x: x.replace(df1.loc[x,'X']))
print(df)

Output: 输出:

    A   B   C
0   2  15   5
1   5  17  10
2  10  21  15

Note df1.set_index('#',inplace = True) set '#' column like index . 注意 df1.set_index('#',inplace = True)'#'列设置为index。 if this column was already the index it is not necessary to execute it 如果此列已经是索引,则无需执行它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM