How to Loop Over Multiple Dataframes and Produce Multiple List

Looping to modify multiple Dataframes in a list

You can wrap your operations in a function and then return & assign the results back:

def add_dummies(df, col_name="Fuel_Type", prefix="Fuel"):
dummies = pd.get_dummies(df[col_name], prefix=prefix)
df = pd.concat([dummies, df], axis=1)
df = df.drop(col_name, axis=1)
return df


df_list = [df1, df2, df3, df4, df5]

df1, df2, df3, df4, df5 = [add_dummies(df) for df in df_list]

# or
# df1, df2, df3, df4, df5 = map(add_dummies, df_list)

The reason yours is not modifying dataframes is that you are reassigning k in pd.concat line and from then on, it "points" to another object which is different than df_j for each j.

Looping through multiple lists

Have revised according to updated question. Note that the input now shown in the question are numeric vectors, not R lists.

First create a named list L using mget and then apply na.aggregate to each component of L and finally write the components back out to the global environment; however, you might want to just keep the result as L2 since it is harder to debug code that overwrites variables.

library(zoo)

nms <- c("a", "b", "e", "f")

L <- mget(nms)
L2 <- lapply(L, na.aggregate)
list2env(L2, .GlobalEnv)

This would also work in place of the last 3 lines.

for(nm in nms) assign(nm, na.aggregate(get(nm)))


Related Topics



Leave a reply



Submit