user10534337
user10534337

Reputation:

add data from different excel files using python

I had a code that work perfectly for 2 files. But now, I want to add several excel files but it's not working.

Here is my code :

import pandas as pd

a = pd.read_excel('alex.xlsx', index_col=None, header=None)
b = pd.read_excel('blago.xlsx', index_col=None, header=None)
c = pd.read_excel('claude.xlsx', index_col=None, header=None)
d = pd.read_excel('cristian.xlsx', index_col=None, header=None)
e = pd.read_excel('eric.xlsx', index_col=None, header=None)
f = pd.read_excel('haou.xlsx', index_col=None, header=None)
g = pd.read_excel('iulian.xlsx', index_col=None, header=None)
h = pd.read_excel('luca.xlsx', index_col=None, header=None)
i = pd.read_excel('maricel.xlsx', index_col=None, header=None)
j = pd.read_excel('michel.xlsx', index_col=None, header=None)
k = pd.read_excel('noel.xlsx', index_col=None, header=None)
l = pd.read_excel('paul.xlsx', index_col=None, header=None)




z = a.add(b, c, d, e, f, g, h, i, j, k, l, fill_value=0)

z.to_excel("z.xlsx")




Upvotes: 0

Views: 31

Answers (1)

megamind
megamind

Reputation: 75

The add function doesn't join two dataframes, it adds to the values in a dataframe. I suggest using concat instead and also using the glob module to avoid a separate call for each individual file like so:

import pandas as pd
import glob

a = pd.concat([pd.read_excel(file, index_col=None, header=None) for file in glob.glob('*.xlsx')], ignore_index = True)
a.fillna(0, inplace = True)
a.to_excel("a.xlsx")

Upvotes: 1

Related Questions