Python:其中一个为空的 Concat 数据帧
Python: Concat dataframes where one of them is empty
我有以下数据框:
df1 = pd.DataFrame(index = [0], columns=['price', 'action', 'amount'])
df1['price'] = 3
df1['action'] = 'deposit'
df1['amount'] = 2
df2 = pd.DataFrame()
其中 df1 代表存款,df2 代表取款。我想把它们连接起来得到
df:
price action amount
0 3 deposit 2
1 nan withdrawal nan
我正在调用一个提取提款和存款的 API。到目前为止,还没有取款,但我想在执行代码时显示为“df”。
关于如何在不进行硬编码的情况下做到这一点有什么建议吗?
谢谢。
使用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
我有以下数据框:
df1 = pd.DataFrame(index = [0], columns=['price', 'action', 'amount'])
df1['price'] = 3
df1['action'] = 'deposit'
df1['amount'] = 2
df2 = pd.DataFrame()
其中 df1 代表存款,df2 代表取款。我想把它们连接起来得到
df:
price action amount
0 3 deposit 2
1 nan withdrawal nan
我正在调用一个提取提款和存款的 API。到目前为止,还没有取款,但我想在执行代码时显示为“df”。
关于如何在不进行硬编码的情况下做到这一点有什么建议吗?
谢谢。
使用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