<p>首先<a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer">^{<cd1>}</a>将<code>index</code>转换为列,以避免在<a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer">^{<cd3>}</a>中丢失,然后使用<a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.unstack.html" rel="nofollow noreferrer">^{<cd5>}</a>将<a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer">^{<cd4>}</a>重新整形,使用<a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html" rel="nofollow noreferrer">^{<cd6>}</a>仅删除缺少的列,最后使用<code>map</code>将<code>MultiIndex</code>展平:</p>
<pre><code>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
</code></pre>