[英]How to append a dataframe to another one (with the same column size) when the column names are different
Is there a way to merge two dataframes with the same number of columns but with different names? 有没有一种方法可以合并两个具有相同列数但名称不同的数据框? The
concat
, merge
, and join
methods do not seem to work for this task. concat
, merge
和join
方法似乎不适用于此任务。 For example, I want to combine these two: 例如,我要结合这两个:
#dataframe1:
columnA | columnB
15 | 23
#dataframe2:
columnC | columnD
12 | 29
Into this: 变成这个:
#dataframe3:
anyColumnName1 | anyColumnName1
15 | 23
12 | 29
Please note that I have 90 columns in my case. 请注意,我的情况下有90列 。
You could rename the columns of the second dataframe first. 您可以先重命名第二个数据框的列。
If they have the same number of columns then simply: 如果它们具有相同的列数,则只需:
dataframe2.columns = dataframe1.columns
and then concat them. 然后吸引他们。
You can use numpy.concatenate
with DataFrame
constructor: 您可以将
numpy.concatenate
与DataFrame
构造函数一起使用:
print (np.concatenate([df1, df2]))
[[15 23]
[12 29]]
df = pd.DataFrame(np.concatenate([df1, df2]), columns=['a','b'])
print (df)
a b
0 15 23
1 12 29
You could use append
by renaming columns of second dataframe based on first. 您可以通过基于第一个重命名第二个数据框的列来使用
append
。
In [304]: df1.append(df2.rename(columns=dict(zip(df2.columns, df1.columns))))
Out[304]:
columnA columnB
0 15 23
0 12 29
Details. 细节。
In [308]: df1
Out[308]:
columnA columnB
0 15 23
In [309]: df2
Out[309]:
columnC columnD
0 12 29
In [310]: dict(zip(df2.columns, df1.columns))
Out[310]: {'columnC': 'columnA', 'columnD': 'columnB'}
In [311]: df2.rename(columns=dict(zip(df2.columns, df1.columns)))
Out[311]:
columnA columnB
0 12 29
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.