0

I have a two dataframes, and I am trying to concatenate these two dataframes into one based on corresponding date index and write into a csv file. "test1.txt" file is given below:

date           f1   f2   f3 
'01-01-2020'   10   20   30
'01-02-2020'   40   70   120
'01-03-2020'   50   80   110
'01-04-2020'   60   90   100

"test2.txt" is given below:

date           f4 
'01-03-2020'   250
'01-04-2020'   260


import pandas as pd
import numpy as np
df_all=pd.read_csv("test1.txt", sep="\t", parse_dates=['date'])
df=pd.read_csv("test2.txt", sep="\t", parse_dates=['date'])

For both df, and df_all dataframes indexed by date column. I am trying merge these into a given dataframe:

date           f1   f2   f3   f4
'01-01-2020'   10   20   30   NAN
'01-01-2020'   40   70   120  NAN
'01-03-2020'   50   80   110  250
'01-04-2020'   60   90   100  260 

Is there any way how to convert these two files into a given format and write into a file efficiently?

user3104352
  • 853
  • 10
  • 26
  • 1
    Use: `pd.merge(df_all, df, how='left').to_csv('data.csv', index=False)`. I am assuming `df_all` is the first dataframe in your example. – David Erickson Dec 28 '20 at 07:08

0 Answers0