gpt4 book ai didi

python - 如何使用 Python pandas Df 将 csvs 与超过 1 个相同的列合并并仅添加不同的列

转载 作者:行者123 更新时间:2023-11-28 22:29:31 27 4
gpt4 key购买 nike

这道题类似于简单的mysql操作-

UPDATE hpaai_month_div t, fahafa_monthly s SET t.col1=s.col1 WHERE t.col2=s.col2 AND t.year=s.year AND t.month=s.month;

Data :

CSV Amonth    year   col2      col1abc      2000   DEFSSDS   190def      2001   GHISFDS   210ghi      2002   SJDYHGF   910CSV Bmonth   year    col2     col1    stat_fipsabc     2000    DEFSSDS   0        adef     2001    GHISFDS   0        bghi     2002    SJDYHGF   0        cResulting CSV :month    year   col2      col1    stat_fipsabc     2000    DEFSSDS   190       adef     2001    GHISFDS   210       bghi     2002    SJDYHGF   910       c

Code so far : (not working as desired)

   df_a = pd.read_csv('a.csv')
df_b = pd.read_csv('b.csv')
merged_df = pd.merge(df_a, df_b, on="col1", how="left")

merged_df = pd.concat([merged_df], axis=1)
merged_df.to_csv('final_output.csv', encoding='utf-8', index=False)
print open('final_output.csv').read()

如何获取数据作为结果csv

最佳答案

看来你需要merge , 最后删除列 col_:

#default inner join 
df = pd.merge(df1, df2, on=['col2','year','month'], suffixes=('','_'))
.drop('col1_',axis=1)
print (df)
month year col2 col1 stat_fips
0 abc 2000 DEFSSDS 190 a
1 def 2001 GHISFDS 210 b
2 ghi 2002 SJDYHGF 910 c

df = pd.merge(df1, df2, on=['col2','year','month'])
print (df)
month year col2 col1_x col1_y stat_fips
0 abc 2000 DEFSSDS 190 0 a
1 def 2001 GHISFDS 210 0 b
2 ghi 2002 SJDYHGF 910 0 c


df = pd.merge(df1, df2, on=['col2','year','month'], suffixes=('','_'))
print (df)
month year col2 col1 col1_ stat_fips
0 abc 2000 DEFSSDS 190 0 a
1 def 2001 GHISFDS 210 0 b
2 ghi 2002 SJDYHGF 910 0 c

关于python - 如何使用 Python pandas Df 将 csvs 与超过 1 个相同的列合并并仅添加不同的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42977418/

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