如何按列和索引连接Pandas DataFrame?

时间:2017-05-19 07:44:26

标签: python pandas

我有四个带有数字列和索引的Pandas DataFrames:

A = pd.DataFrame(data={"435000": [9.792, 9.795], "435002": [9.825, 9.812]}, index=[119000, 119002])
B = pd.DataFrame(data={"435004": [9.805, 9.783], "435006": [9.785, 9.78]}, index=[119000, 119002])
C = pd.DataFrame(data={"435000": [9.778, 9.743], "435002": [9.75, 9.743]}, index=[119004, 119006])
D = pd.DataFrame(data={"435004": [9.743, 9.743], "435006": [9.762, 9.738]}, index=[119004, 119006])

enter image description here

我想将它们连接成一个这样的DataFrame,匹配列名和索引:

enter image description here

如果我尝试pd.concat四个dfs,它们会堆叠在一起(上方和下方,或侧面,取决于axis),我最终会得到NaN个值df:

result = pd.concat([A, B, C, D], axis=0)

enter image description here

如何使用pd.concat(或mergejoin等)来获得正确的结果?

2 个答案:

答案 0 :(得分:4)

你需要成对联合:

result = pd.concat([pd.concat([A, C], axis=0), pd.concat([B, D], axis=0)], axis=1)
print (result)
        435000  435002  435004  435006
119000   9.792   9.825   9.805   9.785
119002   9.795   9.812   9.783   9.780
119004   9.778   9.750   9.743   9.762
119006   9.743   9.743   9.743   9.738

最好的是stack + concat + unstack

result = pd.concat([A.stack(), B.stack(), C.stack(), D.stack()], axis=0).unstack()
print (result)
        435000  435002  435004  435006
119000   9.792   9.825   9.805   9.785
119002   9.795   9.812   9.783   9.780
119004   9.778   9.750   9.743   9.762
119006   9.743   9.743   9.743   9.738

更有活力:

dfs = [A,B,C,D]
result = pd.concat([df.stack() for df in dfs], axis=0).unstack()
print (result)
        435000  435002  435004  435006
119000   9.792   9.825   9.805   9.785
119002   9.795   9.812   9.783   9.780
119004   9.778   9.750   9.743   9.762
119006   9.743   9.743   9.743   9.738

答案 1 :(得分:2)

您也可以使用加入:

pd.concat((A.join(B), C.join(D)))
Out: 
        435000  435002  435004  435006
119000   9.792   9.825   9.805   9.785
119002   9.795   9.812   9.783   9.780
119004   9.778   9.750   9.743   9.762
119006   9.743   9.743   9.743   9.738