映射2个数据框并替换目标数据框中匹配值的标头

时间:2018-07-27 05:17:14

标签: python pandas dataframe

我有一个数据框:df1

  SAP_Name  SAP_Class  SAP_Sec
  Avi       5          C 
  Rison     6          A 
  Slesh     7          B 
  San       8          C 
  Sud       7          B 

df2:

Name_Fi Class

Avi     5 
Rison   6 
Slesh   7 

我正在尝试将df2与df1匹配,以使匹配的值的标头应与df1相同。

SAP_Name  SAP_Class
 Ankan          5
 Rison          6
 Slesh          7

下面是我正在使用的代码:

d = {}
for col2 in df2.columns:
    for col1 in df1.columns:
        cond = df2[col2].isin(df1[col1]).all()
        if cond:
           d[col2] = col1
df2 = df2.rename(columns=d)
print (df2)

我可以在一个小文件中获得所需的输出,但是我的实际文件有112444行×446列,要更改的目标文件有3行×35列,代码在Windows中长时间运行这个案例。有人可以在这里帮助我吗?

2 个答案:

答案 0 :(得分:2)

我认为如果性能很重要,请将issubsetset结合使用:

d = {}
for col2 in df2.columns:
    for col1 in df1.columns:
        cond = set(df2[col2]).issubset(df1[col1])
        if cond:
           d[col2] = col1
df2 = df2.rename(columns=d)
print (df2)
  SAP_Name  SAP_Class
0      Avi          5
1    Rison          6
2    Slesh          7

编辑:

#create dictioanry of Series without dupes
dfs1 = {col1: df1[col1].drop_duplicates() for col1 in df1.columns}
#print (dfs1)

#create dictionary of sets
set2 = {col2: set(df2[col2]) for col2 in df2.columns}
#print (set2)

#loop buy both dictionaries and find columns for rename
d = {}
for col2, v2 in set2.items():
    for col1, v1 in dfs1.items():
        cond = v2.issubset(v1)
        if cond:
           d[col2] = col1
df2 = df2.rename(columns=d)
print (df2)
  SAP_Name  SAP_Class
0      Avi          5
1    Rison          6
2    Slesh          7

答案 1 :(得分:2)

我重命名了列并使用合并。

cols = ['SAP_Name', 'SAP_Class']
df2.set_axis(cols, axis=1, inplace=False).merge(df1[cols])

  SAP_Name  SAP_Class
0      Avi          5
1    Rison          6
2    Slesh          7