Home > Enterprise >  Is there a way to manipulate each data frame in a list of data frames and assign the new data frame
Is there a way to manipulate each data frame in a list of data frames and assign the new data frame

Time:04-21

Suppose the below setup:

import numpy as np
import pandas as pd
index = pd.date_range('1/1/2022', periods=10)
a = {'a': np.random.random(10)}
b = {'b': np.random.random(10)}
c = {'c': np.random.random(10)}
a_df = pd.DataFrame(a, index=index)
b_df = pd.DataFrame(b, index=index)
c_df = pd.DataFrame(c, index=index)

So instead of doing the following:

a_df = a_df[a_df.index.dayofweek < 5]
b_df = b_df[b_df.index.dayofweek < 5]
c_df = c_df[c_df.index.dayofweek < 5]

I'm wondering if I put the df's in a list as such:

df_list = [a_df, b_df, c_df]

if there's a way to do this with a list comprehension? The assignment is the part I'm unsure how to do in a list comp.

CodePudding user response:

I think I got it.

df_list = [i[i.index.dayofweek<5] for i in df_list] 

CodePudding user response:

Yep, you are right.

>>> foo = [df[df.index.dayofweek < 5] for df in df_list]
>>> foo[1]
                   b
2022-01-03  0.214746
2022-01-04  0.543250
2022-01-05  0.320643
2022-01-06  0.027947
2022-01-07  0.327104
2022-01-10  0.149649

  • Related