gpt4 book ai didi

Python Pandas Vlookup

转载 作者:行者123 更新时间:2023-12-04 20:02:42 25 4
gpt4 key购买 nike

我正在尝试通过在 Python 中使用 excel 中的 Vlookup 函数来合并两个 excel 文件。
根据我的代码,结果将是:

col1_x | col2_x | col3_x | col4_y | col5_y | col6_y 
1 2 3 4 5 6
7 8 9 10 11 12
我的代码:
df1 = pd.read_excel("dropped_file.xlsx")
df2 = pd.read_excel("original.xlsx")

result = pd.merge(df1, df2, on = ['col1', 'col3', 'col4'], how='left')
result.to_excel("result.xlsx", index=False)
有人知道在列名后面去掉 _x 和 _y 吗?

最佳答案

_x 的原因和 _y合并后是重复的列名。所以为了避免col1 , col1 , col2 , col2添加列 _x , _y所以输出是 col1_x , col1_y , col2_x , col2_y .
如果需要删除_x, _y但输出将是重复的列使用 Series.str.replace :

df.columns = df.columns.str.replace('_x|_y','', regex=True)
print (df)
col1 col2 col3 col4 col5 col6
0 1 2 3 4 5 6
1 7 8 9 10 11 12

关于Python Pandas Vlookup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66899678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com