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

Pass the name of the dataframe into each for row for a new column in a list of dataframes Python

I have a list of dataframes, I want to add a new column to each dataframe that is the name of the dataframe.

df_all = [df1,df2,df3]

for df in df_all:
    df["Loc"] = df[df].astype.(str)

Boolean array expected for the condition, not object

is this possible to achieve?

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 :

You can’t do this, python objects have no possibility to know their name(s).

You could emulate it with:

df_all = [df1, df2, df3]

for i, df in enumerate(df_all, start=1):
    df['Loc'] = f'df{i}'

Alternatively, use a dictionary:

df_all = {'df1': df1, 'df2': df2, 'df3': df3}

for k, df in df_all.items():
    df['Loc'] = k
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