asd
asd

Reputation: 1309

Use dataframe name to add column

I have 2 dataframes, fruit and price.

fruit
       fruits   price
0      apple     110

sports
       fruits   price
0      football   110

I need to perform a loop. But first, I need to know which dataframes each are. I tried

lista = [fruit, sports]

for x in lista:
     x['dataframe_name] = f'{x}'
     ...

Expected Output:

fruit  
       fruits  price   dataframe_name
0       apple   110      fruit

Upvotes: 0

Views: 57

Answers (1)

Scott Boston
Scott Boston

Reputation: 153560

You could try something like this using a dictionary of dataframes and pd.concat to loop over with keys holding the names of each of those dataframes:

df_fruit = pd.DataFrame({'fruits':['apple'], 
                        'price':[110]})

df_sports = pd.DataFrame({'fruits':['football'],
                         'price':[110]})

lista = [df_fruit, df_sports]

df_con = pd.concat(lista, keys=['fruits', 'sports'])

for n, g in df_con.groupby(level=0):
    print(n)
    print(g.loc[n])
    print('\n')

Output:

fruits
  fruits  price
0  apple    110


sports
     fruits  price
0  football    110

Upvotes: 2

Related Questions