3

I have four df (df1,df2,df3,df4)

Sometimes df1 is null, sometimes df2 is null, sometimes df3 and df4 accordingly.

How can I do an outer merge so that the df which is empty is automatically ignored? I am using the below code to merge as of now:-

df = f1.result().merge(f2.result(), how='left', left_on='time', right_on='time').merge(f3.result(), how='left', left_on='time', right_on='time').merge(f4.result(), how='left', left_on='time', right_on='time')

and

df = reduce(lambda x,y: pd.merge(x,y, on='time', how='outer'), [f1.result(),f2.result(),f3.result(),f4.result()])

2 Answers 2

1

You can use df.empty attribute or len(df) > 0 to check whether the dataframe is empty or not.

Try this:

dfs = [df1, df2, df3, df4]
non_empty_dfs = [df for df in dfs if not df.empty]

df_final = reduce(lambda left,right: pd.merge(left,right, on='time', how='outer'), non_empty_dfs)

Or, you could also filter empty dataframe as,

non_empty_dfs = [df for df in dfs if len(df) > 0]
Sign up to request clarification or add additional context in comments.

Comments

1

use pandas' dataframe empty method, to filter out the empty dataframe, then you can concatenate or run whatever merge operation you have in mind:

df4 = pd.DataFrame({'A':[]}) #empty dataframe
df1 = pd.DataFrame({'B':[2]})
df2 = pd.DataFrame({'C':[3]})
df3 = pd.DataFrame({'D':[4]})

dfs = [df1,df2,df3,df4]

#concat
#u can do other operations since u have gotten rid of the empty dataframe

pd.concat([df for df in dfs if not df.empty],axis=1)

    B   C   D
0   2   3   4

2 Comments

This works but supposes if one of the df has some missing DateTime index rows then it shifts the values. and do not return null for nonmatching values. Suppose none of them are empty df but if df2 has four missing values then it shifts the values and always returns the last four rows as null.
yes, but that's why I specified merging. Thanks a lot for your answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.