简体   繁体   中英

Pandas combine multiple csv files

I have multiple csv files that I would like to combine into one df.

They are all in this general format, with two index columns:

                                           1     2
CU0112-005287-7 Output Energy, (Wh/h)   0.064   0.066
CU0112-005287-7 Lights (Wh)                0     0

                                            1     2
CU0112-001885-L Output Energy, (Wh/h)   1.33    1.317
CU0112-001885-L Lights (Wh)             1.33    1.317

and so on...

The combined df would be:

                                           1     2
CU0112-005287-7 Output Energy, (Wh/h)   0.064   0.066
CU0112-005287-7 Lights (Wh)                0     0
CU0112-001885-L Output Energy, (Wh/h)   1.33    1.317
CU0112-001885-L Lights (Wh)             1.33    1.317

I am trying this code:

import os
import pandas as pd
import glob

files = glob.glob(r'2017-12-05\Aggregated\*.csv')   //folder which contains all the csv files

df = pd.merge([pd.read_csv(f, index_col=[0,1])for f in files], how='outer')

df.to_csv(r'\merged.csv')

But I am getting this error:

TypeError: merge() takes at least 2 arguments (2 given)

我认为您需要concat而不是merge

df = pd.concat([pd.read_csv(f, index_col=[0,1]) for f in files])

You can try the following. I made some changes to the DataFrame combining logic

import os
import pandas as pd
import glob

files = glob.glob(r'2017-12-05\Aggregated\*.csv')   //folder which contains all the csv files

df = reduce(lambda df1,df2: pd.merge(df1,df2,on='id',how='outer'),[pd.read_csv(f, index_col=[0,1])for f in files] )

df.to_csv(r'\merged.csv')

A simple way:

Creating a list with the names of csvs:

files=listdir()
csvs=list()
for file in files:
    if file.endswith(".csv"):
        csvs.append(file)

concatenate the csvs:

data=pd.DataFrame()
for i in csvs:
    table=pd.read_csv(i)
    data=pd.concat([data,table])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM