2 回答
TA贡献1840条经验 获得超5个赞
首先DataFrame.meltwith 转换index为 column 以避免在DataFrame.merge左连接中丢失,然后通过DataFrame.set_indexwith重新整形DataFrame.unstack,仅删除缺少的列DataFrame.dropna,最后MultiIndex用展平map:
df = (df_main.reset_index()
.melt('index',var_name='Column', value_name='ID')
.merge(df_map, how='left')
.set_index(['index', 'Column'])
.unstack()
.rename_axis(None)
.dropna(how='all', axis=1))
df.columns = df.columns.map('_'.join)
print (df)
ID_A1 ID_A5 ID_B7 ID_C17 ID_C19 Value_A1 Value_B7 Value_C17
0 3 5 7 17 19 ValA1 ValB7 ValC17
1 6 10 14 34 38 NaN NaN NaN
TA贡献1805条经验 获得超10个赞
Series.map和pandas.concat的替代解决方案:
df2=pd.concat([df_main.T[key].map(df_map.set_index('ID')['Value']) for key in df_main.index.tolist()],axis=1).T.add_prefix('Value_')
df_main=pd.concat([df_main,df2],axis=1)
df_main.dropna(how='all',axis=1,inplace=True)
print(df_main)
A3 A5 B7 C17 C19 Value_A3 Value_B7 Value_C17
0 3 5 7 17 19 ValA1 ValB7 ValC17
1 6 10 14 34 38 NaN NaN NaN
添加回答
举报