我正在尝试合并两个包含相同键列的数据帧.其他一些列也有相同的标题,虽然不是相同数量的行,并且在合并这些列之后,使用postscript _x,_y等对原始标题进行"复制".
有谁知道如何让pandas删除下面示例中的重复列?
这是我的python代码:
import pandas as pd
holding_df = pd.read_csv('holding.csv')
invest_df = pd.read_csv('invest.csv')
merge_df = pd.merge(holding_df, invest_df, on='key', how='left').fillna(0)
merge_df.to_csv('merged.csv', index=False)
Run Code Online (Sandbox Code Playgroud)
CSV文件包含以下内容:
左数据帧的第一行(holding_df)
key, dept_name, res_name, year, need, holding
DeptA_ResA_2015, DeptA, ResA, 2015, 1, 1
DeptA_ResA_2016, DeptA, ResA, 2016, 1, 1
DeptA_ResA_2017, DeptA, ResA, 2017, 1, 1
...
Run Code Online (Sandbox Code Playgroud)
右数据帧(invest_df)
key, dept_name, res_name, year, no_of_inv, inv_cost_wo_ice
DeptA_ResA_2015, DeptA, ResA, 2015, 1, 1000000
DeptA_ResB_2015, DeptA, ResB, 2015, 2, 6000000
DeptB_ResB_2015, DeptB, ResB, 2015, 1, 6000000
...
Run Code Online (Sandbox Code Playgroud)
合并结果
key, dept_name_x, res_name_x, year_x, need, holding, dept_name_y, res_name_y, year_y, no_of_inv, inv_cost_wo_ice
DeptA_ResA_2015, DeptA, ResA, 2015, 1, 1, DeptA, ResA, 2015.0, 1.0, 1000000.0
DeptA_ResA_2016, DeptA, ResA, 2016, 1, 1, 0, 0, 0.0, 0.0, 0.0
DeptA_ResA_2017, DeptA, ResA, 2017, 1, 1, 0, 0, 0.0, 0.0, 0.0
DeptA_ResA_2018, DeptA, ResA, 2018, 1, 1, 0, 0, 0.0, 0.0, 0.0
DeptA_ResA_2019, DeptA, ResA, 2019, 1, 1, 0, 0, 0.0, 0.0, 0.0
...
Run Code Online (Sandbox Code Playgroud)
您有带有后缀“_x”和“_y”的附加列的原因是因为您要合并的列没有匹配的值,因此这种冲突会产生附加列。在这种情况下,您需要删除额外的 '_y' 列并重命名 '_x' 列:
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
Run Code Online (Sandbox Code Playgroud)
编辑 如果您将公共列添加到合并中,则除非这些列上的匹配项不匹配,否则它不应生成重复的列:
merge_df = pd.merge(holding_df, invest_df, on=['key', 'dept_name', 'res_name', 'year'], how='left').fillna(0)
Run Code Online (Sandbox Code Playgroud)
即使列的数据相同,左连接后的重复列也存在同样的问题.我做了一个查询,发现即使两个列都是pandas 0.14中的NaN,NaN值也被认为是不同的.但是一旦你升级到0.15,这个问题就会消失,这就解释了为什么它后来适合你,你可能已经升级了.