[英]Append new Pandas DataFrame to an old one without column names sorted
I append a new dataframe to an old one: 我将新的数据框附加到旧的数据框:
import numpy as np
import pandas as pd
from pandas import Series
from pandas import DataFrame
df1 = DataFrame(np.arange(3.).reshape((1, 3)), columns=list('dcb'), index=['Ohio'])
df2 = DataFrame(np.arange(3.).reshape((1, 3)), columns=list('bdc'), index=['Utah'])
print df1
print df2
print pd.concat([df1, df2])
then i got result like this: 然后我得到这样的结果:
d c b
Ohio 0.0 1.0 2.0
b d c
Utah 0.0 1.0 2.0
b c d
Ohio 2.0 1.0 0.0
Utah 0.0 2.0 1.0
however i want the columns in the result not sorted as 'bcd' but as origin 'dcb' like: 但是我希望结果中的列不按“ bcd”排序,而是按原点“ dcb”排序:
d c b
Ohio 0.0 1.0 2.0
Utah 1.0 2.0 0.0
使用join_axes
参数:
pd.concat([df1, df2], join_axes=[df1.columns])
You can store the original order in a variable and then reapply it after combining: 您可以将原始订单存储在变量中,然后在合并后重新应用它:
df1 = DataFrame(np.arange(3.).reshape((1, 3)), columns=list('dcb'), index=['Ohio'])
orig_column_order = df1.columns
df2 = DataFrame(np.arange(3.).reshape((1, 3)), columns=list('bdc'), index=['Utah'])
combined = pd.concat([df1, df2], keys=list('dbc'))
combined = combined[orig_column_order]
print(df1)
print(df2)
print(combined)
Gives: 给出:
d c b
Ohio 0.0 1.0 2.0
b d c
Utah 0.0 1.0 2.0
d c b
d Ohio 0.0 1.0 2.0
b Utah 1.0 2.0 0.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.