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; so I want go over the ABC df and if the number matches the # of df1 to replace it with the X value
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
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:
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 . if this column was already the index it is not necessary to execute it
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.