Home > Software design >  How to simplify the for loop of dataframe?
How to simplify the for loop of dataframe?

Time:12-26

I am wondering to simplify these similar codes, it seems to be easy but I couldn’t make it.

df_ls1_speci = []
for df in df_ls1:
    value = pd.Series(df.values.ravel('F'))
    value = list(value[len(df["column"]):])
    df_ls1_speci.append(value)

df_ls_speci = []
for df in df_ls:
    value = pd.Series(df.values.ravel('F'))
    value = list(value[len(df["column"]):])
    df_ls_speci.append(value)

df_ls and df_ls1 are both types of dataframe. If I write

for df in df_ls, df_ls1:

It couldn’t work, because 'list' object has no attribute 'values'. So other methods to solve it?

CodePudding user response:

This depends on what you are trying to solve, if you want to do the looping twice in list of dataframe to create two lists, you might consider writing it into function.

def dataframe_list_to_list(df_ls)
    out_df_ls_speci = []
    for df in df_ls:
        value = pd.Series(df.values.ravel('F'))
        value = list(value[len(df["column"]):])
        out_df_ls_speci.append(value)
    return out_df_ls_speci

df_ls1_speci = dataframe_list_to_list(df_ls1)
df_ls_speci = dataframe_list_to_list(df_ls)

If you want to get only one output, then you can concatenate two list and loop once -- you can still use the function shown above.

df_ls_all = dataframe_list_to_list(df_ls1   df_ls)
  • Related