将一个数据框中的一列元素添加到另一数据框中的另一列的元素

时间:2019-02-25 12:12:05

标签: python-3.x pandas dataframe

嗨,我有以下数据框

enter image description here

我想将Df2中M / O列的元素添加到Df1中A / O列的元素。对于Df2 M / L到Df1 A / L同样如此。

这两个数据框的列名都有2个级别。

enter image description here

我正在尝试以下操作,但没有将Df2的第五行添加到Df1:

Df1 = {('A','O'): [5, 6, 7, 8], ('A','L'): [9, 10, 11, 12], ('G','O'): [2, 2, 2, 2], ('G','L'): [3, 3, 3, 3]}
index1 =[1,2,3,4]
Df1 = pd.DataFrame(data=Df1, index=index1)
Df2 = {('M','O'): [1, 2, 3, 4], ('M','L'): [5, 6, 7, 8], ('S','O'): [1, 1, 1, 1], ('S','L'): [1, 1, 1, 1]}
index2 =[1,2,3,5]
Df2 = pd.DataFrame(data=Df2, index=index2)

    for profile in ["O", "L"]:
    Df1[("A", profile)] = Df1[("A", profile)].add(Df2[("M", profile)], fill_value=0)

你知道为什么吗?

谢谢

1 个答案:

答案 0 :(得分:1)

您可以将xsdrop_level=False一起使用,以返回MultiIndex DataFrame,然后将rename的顶级与A的{​​{1}}级别对齐:

Df1
相关问题