Skip to content Skip to sidebar Skip to footer

How To Convert String To A Dataframe Name Pandas/python

I have 2 dataframes (dfA, dfB) I have another dataframe dfC which has a column called 'SOURCE'. Values of SOURCE will either be dfA or dfB. I am trying to go row by row on dfC and

Solution 1:

Just use if-else in your loop;

for ind in range(dfC.shape[0]):
   if dfC.loc[ind, 'SOURCE'] == 'dfA':
       "do what you want to dfA"
   if dfC.loc[ind, 'SOURCE'] == 'dfB':
           "do what you want to dfB"

Does this sound reasonable?

Solution 2:

I suggest to use pandas.DataFrame.update which updates dataframe based on index.

dfa = DataFrame([[2],[4]], index=[1,2], columns=['val'])
dfb = DataFrame([[4],[8]], index=[1,2], columns=['val'])
dfc = DataFrame([['dfa',-1],['dfb',-2],['dfa',-3]], index=[1,1,2], columns='dest','val'])

dfa.update(dfc[dfc['dest']=='dfa'])
dfb.update(dfc[dfc['dest']=='dfb'])

Using for loop in pandas is usually discouraged.

Post a Comment for "How To Convert String To A Dataframe Name Pandas/python"