I want to read csv files in a for loop using pandas. I have put the names of the files in a list. After each iteration each file has to be appended to result. Using the folowing code I can only append one file:
import pandas as pd
files = ['fileA.csv' , 'fileB.csv']
result = None
for files in files:
df1 = pd.read_csv(files)
df1['JourneyID'] = 'Journey2'
df1.set_index( 'JourneyID', inplace=True)
df1b = df1.head(15)
if result is None:
result = df1b
else:
result.append(df1b)
result.head(30)
Any help please?
if/elseshould be inside the for loopdf.appendreturns a new DataFrame - it doesn't update the frame inplace... It's not ideal as you probably want to handle this a different way (depending on what you need/constraints), but you can useresult = result.append(df1b)in theelse... to bindresultto be the actual new dataframe so it keeps the previous and new elements each loop...