Home > Enterprise >  Convert a list of strings to objects
Convert a list of strings to objects

Time:01-05

I have 10 small dataframes, offer_1_activity,offer_2_activity,...,offer_10_activity.Each of these df's have a common column customer id. I want to merge all of these together into a single dataframe 'offers_activity'.

from functools import reduce
offers_activity = reduce(lambda  left,right: pd.merge(left,right,on=['customer_id'],
                                            how='outer'), offers_df_list)

Created 'offers_df_list' using a loop

offers_df_list=[]
for i in range(1,11):
    offers_df_list.append('offer_{}_activity'.format(i))

values in 'offers_df_list' are of type string.so i am getting the following error

TypeError: Can only merge Series or DataFrame objects, a <class 'str'> was passed

Is there any other way to convert this str list to object type list instead of hardcoding like below?

offers_df_list=[offer_1_activity,offer_2_activity,...,offer_10_activity]

CodePudding user response:

You can access the DataFrames from the locals() table -

x_1 = pd.DataFrame({'A': [1, 2, 3], 'B': [1, 2, 3]})
x_2 = pd.DataFrame({'A': [1, 2, 3], 'BB': [11, 12, 13]})

for i in range(1, 3):
    xs.append(locals()[f'x_{i}'])

x_all = reduce(lambda left, right: pd.merge(left, right, on=['A'], how='outer'), xs)
  •  Tags:  
  • Related