python - 如何按列和索引连接 Pandas DataFrames?

标签 python pandas

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

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 四个 df,它们会堆叠(根据 axis 的不同,它们会堆叠在一起(在上方和下方,或在侧面),我最终会在 df 中具有 NaN 值:

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

enter image description here

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

最佳答案

你需要成对连接:

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

关于python - 如何按列和索引连接 Pandas DataFrames?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44064299/

相关文章:

python - 使用groupby函数时如何将元素粘合到列表中?

python pandas 过滤并聚合多列并写入CSV

python - pd.Series.cat.as_ordered() 在 Pandas 中做什么?

python - 绘图类型问题 : TypeError: only size-1 arrays can be converted to Python scalars

python - 在 celery 任务上调用 delay() 后,任务甚至需要 5 到 10 秒以上才能开始执行,以 redis 作为服务器

Python pandas,多行的绘图选项

python-3.x - 如何根据 Excel Dataframe 中的内容突出显示行?

python - 在 Pandas 中,如何根据列中以逗号分隔的项目计数创建数据框?

python - 点亮大容量存储器的 LED

python - OpenCV for ARM (Beagleboard) 使用 YUYV 而不是 JPEG 压缩?