Skip to content
Advertisement

Python: Concat dataframes where one of them is empty

I have the following dataframes:

df1 = pd.DataFrame(index = [0], columns=['price', 'action', 'amount'])
df1['price'] = 3
df1['action'] = 'deposit'
df1['amount'] = 2

df2 = pd.DataFrame()

where df1 represents deposits and df2 represents withdrawals. I want to concat them to get

df:
    price    action     amount
 0  3        deposit    2
 1  nan      withdrawal nan

I am calling an API that fetches withdrawals and deposits. So far, no withdrawals have been made but I want to display that as shown in “df” whenever the code is executed.

Any suggestions on how to do that without hardcoding?

Thank you.

Advertisement

Answer

Use df.empty:

df1 = df1 if not df1.empty else pd.DataFrame({'action': ['deposit']})
df2 = df2 if not df2.empty else pd.DataFrame({'action': ['withdrawal']})
out = pd.concat([df1, df2])
print(out)

# Output
   price      action  amount
0    3.0     deposit     2.0
0    NaN  withdrawal     NaN
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement