【问题标题】:How to use Python pandas Df to merge csvs with more than 1 same column and add only different columns如何使用 Python pandas Df 将具有 1 个以上相同列的 csv 合并并仅添加不同的列
【发布时间】:2017-03-23 13:26:24
【问题描述】:

这道题和简单的mysql操作类似——

更新 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;

数据:

CSV A
月 年 col2 col1
abc 2000 DEFSSDS 190
定义 2001 GHISFDS 210
吉2002 SJDYHGF 910

CSV B
月 年 col2 col1 stat_fips
abc 2000 DEFSSDS 0 一个
def 2001 GHISFDS 0 b
吉2002 SJDYHGF 0 c


生成的 CSV :

月 年 col2 col1 stat_fips
abc 2000 DEFSSDS 190 a
定义 2001 GHISFDS 210 b
吉2002 SJDYHGF 910 c

到目前为止的代码:(无法正常工作)

   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

【问题讨论】:

    标签: python mysql pandas dataframe


    【解决方案1】:

    看来你需要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
    

    【讨论】:

    • 后缀是什么?
    • 如果两个数据框中的列重叠,默认添加_x_y。后缀。参数suffixes 用于更改默认值。
    【解决方案2】:

    如果您提前从'df_b' 中删除'col1',您可以让merge 使用其默认值。

    df_a.merge(df_b.drop('col1', 1))
    
      month  year     col2  col1 stat_fips
    0   abc  2000  DEFSSDS   190         a
    1   def  2001  GHISFDS   210         b
    2   ghi  2002  SJDYHGF   910         c
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-24
      • 2021-08-21
      • 1970-01-01
      • 2014-01-18
      • 2017-01-11
      • 2014-09-28
      • 1970-01-01
      • 2020-05-13
      相关资源
      最近更新 更多