添加两个 pandas 数据框并保留两个索引的最优雅、最有效的方法是什么?
表1
表2
结果表
import pandas as pd
table_one = pd.DataFrame({'Col1': [0.5, 1.0],
'Col2': [0.0, 0.5]},
index=['Sample1', 'Sample2'])
table_two = pd.DataFrame({'Col1': [0.0, 1.0],
'Col2': [1.0, 1.0]},
index=['Sample3', 'Sample4'])
table_result = pd.DataFrame({'Col1': [0.5, 2.0],
'Col2': [1.0, 1.5]},
index=[['Sample1','Sample3'], ['Sample2','Sample4']])
# Please insert solution here...
最佳答案
我会使用:
out = table_one.add(table_two.set_axis(table_one.index))
out.index = zip(table_one.index, table_two.index)
泛化到任意数量的表:
from functools import reduce
tables = [table_one, table_two]
idx = list(zip(*(d.index for d in tables)))
out = reduce(lambda a, b: a.add(b), (d.set_axis(idx) for d in tables))
输出:
Col1 Col2
(Sample1, Sample3) 0.5 1.0
(Sample2, Sample4) 2.0 1.5
关于python - 如何添加两个 pandas 数据框并保留两个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76729370/