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

时间:2019-08-20 18:25:57

标签: python pandas dataframe

我有两个数据框,其中一个的格式为:

#   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 

和以下形式的一个:

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

我想用X值替换第二个数据帧中的所有ABC值;所以我想查看ABC df,如果数字与df1的编号匹配,则将其替换为X值

茶几应该看起来像:

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

有办法吗?

3 个答案:

答案 0 :(得分:3)

IIUC # lib/tasks/active_storage.rake namespace :active_storage do desc 'Ensures all files are mirrored' task mirror_all: [:environment] do # Iterate through each blob ActiveStorage::Blob.all.each do |blob| # We assume the primary storage is local local_file = ActiveStorage::Blob.service.primary.path_for(blob.key) # Iterate through each mirror blob.service.mirrors.each do |mirror| # If the file doesn't exist on the mirror, upload it mirror.upload(blob.key, File.open(local_file), checksum: blob.checksum) unless mirror.exist? blob.key end end end end

replace

答案 1 :(得分:1)

假设您的第一个DataFrame是a,第二个是b,您可以将b列映射到a.x的值,如下所示:

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

结果是:

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

答案 2 :(得分:1)

仅应使用:

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

示例:

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)

输出:

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

注意 df1.set_index('#',inplace = True)设置'#'列为index。 如果该列已经是索引,则无需执行