0

I have 3 dataframes (df1, df2, df3), out of which 'df3' might be created or not. If the dataframe df3 is created then merge all the three else just merge df1 & df2.

I am trying the below code:

df1 = pd.DataFrame([['a',1,2],['b',4,5],['c',7,8],[np.NaN,10,11]], columns=['id','x','y'])
df2 = pd.DataFrame([['a',1,2],['b',4,5],['c',7,10],[np.NaN,10,11]], columns=['id','x','y'])
df3 = pd.DataFrame([['g',1,2],['h',4,5],['i',7,10],[np.NaN,10,11]], columns=['id','x','y'])

if not isinstance(df3, type(None)):
    df1.append(df2)
else:
    df1.append(df2).append(df3)

It is giving me "NameError: name 'df3' is not defined" error if df3 doesnot exist

Shanoo
  • 1,185
  • 1
  • 11
  • 38

1 Answers1

1

This answer might have the key you're looking for: https://stackoverflow.com/a/1592578

df1.append(df2)
try:
  df1.append(df3)
except NameError:
  pass # df3 does not exist
Josh M
  • 11
  • 2