Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to simplify the for loop of dataframe?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading