Python:连接两个不同形状的数据框的行
Python: concat rows of two dataframes of different shapes
我有两个数据框:
df1 = pd.DataFrame(index = [0,1,2], columns=['USD', 'CAD'])
df1['USD'] = [1,2,3]
df1['CAD'] = [4,5,6]
df1:
USD CAD
0 1 4
1 2 5
2 3 6
df2 = pd.DataFrame(index = [0,1], columns = ['currency','balance'])
df2['currency'] = ['USD', 'CAD']
df2['balance'] = [2,3]
df2:
currency balance
0 USD 2
1 CAD 3
我想在索引 0 处向 df1 添加一行,并根据货币用 df2 的余额填充该行。所以最终的 df 应该是这样的:
df:
USD CAD
0 2 3
1 1 4
2 2 5
3 3 6
我怎样才能用 pythonic 方式做到这一点?谢谢
试试下面的代码:
df = pd.concat([df2.set_index('currency').T, df1], axis=0, ignore_index=True)
我有两个数据框:
df1 = pd.DataFrame(index = [0,1,2], columns=['USD', 'CAD'])
df1['USD'] = [1,2,3]
df1['CAD'] = [4,5,6]
df1:
USD CAD
0 1 4
1 2 5
2 3 6
df2 = pd.DataFrame(index = [0,1], columns = ['currency','balance'])
df2['currency'] = ['USD', 'CAD']
df2['balance'] = [2,3]
df2:
currency balance
0 USD 2
1 CAD 3
我想在索引 0 处向 df1 添加一行,并根据货币用 df2 的余额填充该行。所以最终的 df 应该是这样的:
df:
USD CAD
0 2 3
1 1 4
2 2 5
3 3 6
我怎样才能用 pythonic 方式做到这一点?谢谢
试试下面的代码:
df = pd.concat([df2.set_index('currency').T, df1], axis=0, ignore_index=True)