我有两个数据框,如下所示:
dataframeA
bagle scom others
111 222 333
111 222 333
dataframeB
bagle scom others
444 555 666
444 555 666
我想将dataframeA和dataframeB(相同列的名称)合并为:
dataframeA&B
A B C D E F
111 444 222 555 333 666
111 444 222 555 333 666
我该怎么办?
答案 0 :(得分:0)
我认为您不只是对获得特定结果感兴趣,而对更通用的解决方案感兴趣,您需要:
以下代码:
import numpy as np
import pandas as pd
from collections import OrderedDict
# create the DFs
df_1 = pd.DataFrame({'bagle': [111, 111], 'scom': [222, 222], 'others': [333, 333]})
df_2 = pd.DataFrame({'bagle': [444, 444], 'scom': [555, 555], 'others': [666, 666]})
# concat them horizontally
df_3 = pd.concat([df_1, df_2], axis=1)
columns = df_3.columns
# unique list for the builtin pandas renaming to work with similar names
unique_columns = list(OrderedDict.fromkeys(columns))
# final renaming
columns_fixed = [ chr(65 + i) for i in range(len(columns)) ]
# pandas-re-ordering columns before renaming
df_3 = df_3[unique_columns]
# the actual renaming to char-based
df_3.columns = columns_fixed
df_3
##############################
A B C D E F
0 111 444 222 555 333 666
1 111 444 222 555 333 666
参考: