<p>有后缀为''x'和''y'的附加列的原因是,要合并的列没有匹配的值,因此此冲突会产生附加列。在这种情况下,您需要删除附加的'\u y'列并重命名'\u x'列:</p>
<pre><code>In [145]:
# define our drop function
def drop_y(df):
# list comprehension of the cols that end with '_y'
to_drop = [x for x in df if x.endswith('_y')]
df.drop(to_drop, axis=1, inplace=True)
drop_y(merged)
merged
Out[145]:
key dept_name_x res_name_x year_x need holding \
0 DeptA_ResA_2015 DeptA ResA 2015 1 1
1 DeptA_ResA_2016 DeptA ResA 2016 1 1
2 DeptA_ResA_2017 DeptA ResA 2017 1 1
no_of_inv inv_cost_wo_ice
0 1 1000000
1 0 0
2 0 0
In [146]:
# func to rename '_x' cols
def rename_x(df):
for col in df:
if col.endswith('_x'):
df.rename(columns={col:col.rstrip('_x')}, inplace=True)
rename_x(merged)
merged
Out[146]:
key dept_name res_name year need holding no_of_inv \
0 DeptA_ResA_2015 DeptA ResA 2015 1 1 1
1 DeptA_ResA_2016 DeptA ResA 2016 1 1 0
2 DeptA_ResA_2017 DeptA ResA 2017 1 1 0
inv_cost_wo_ice
0 1000000
1 0
2 0
</code></pre>
<p><strong>编辑</strong>
如果将公用列添加到合并中,则不应生成重复的列,除非这些列上的匹配项不匹配:</p>
<pre><code>merge_df = pd.merge(holding_df, invest_df, on=['key', 'dept_name', 'res_name', 'year'], how='left').fillna(0)
</code></pre>