Home > other >  How to concatenate multiple dataframes in sequential order?
How to concatenate multiple dataframes in sequential order?

Time:05-16

I want to go through the whole month of april day by day. I want to print one dataframe that has every day combined up to the day I am at, and another df that has just the last 3 days. For example, lets say today was april 5th 2021. I want to print a dataframe that has combined apr1,apr2,apr3, and apr4 together. I also want to print just the last 3 days (apr2,apr3,apr4). How would I go about doing this?

import pandas as pd
z={
    0 :pd.read_csv('21_apr1.csv'),
    1 :pd.read_csv('21_apr2.csv'),
    2 :pd.read_csv('21_apr3.csv'),
    3 :pd.read_csv('21_apr4.csv'),
    4 :pd.read_csv('21_apr5.csv'),
    }
for w in range(5):
    try:
        df1=pd.concat([z[w],z[w-1],z[w-2],z[w-3],z[w-4]])
    except KeyError:
        continue
for w in range(5):
    try:
        df2=pd.concat([z[w-3],z[w-2],z[w-1]])
    except KeyError:
        continue
print(df1.head(3))
print(df2.head(3))

CodePudding user response:

import pandas as pd
z = [pd.read_csv(f'21_apr{x}.csv') for x in range(1, 6)]

df1 = pd.concat([z[0:-1])
df2 = pd.concat([z[1:-1])

CodePudding user response:

I was able to solve using what BeRT2me wrote.

today = 7
for n in range(1,today):
    if n>3:
        z = [pd.read_csv(f'21_day{w}.csv')for w in range(1,n 1)]
        temp1=pd.read_csv(f'21_day{n-2}.csv')
        temp2=pd.read_csv(f'21_day{n-1}.csv')
        temp3=pd.read_csv(f'21_day{n}.csv')
        last3days=pd.concat([temp1,temp2,temp3])
        all_past = pd.concat(z[:])
        nextday = pd.read_csv(f'21_day{n 1}.csv')

      #run my code in the for loop
  • Related