Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 将一个数据帧中一列的元素添加到另一个数据帧中另一列的元素_Python 3.x_Pandas_Dataframe - Fatal编程技术网

Python 3.x 将一个数据帧中一列的元素添加到另一个数据帧中另一列的元素

Python 3.x 将一个数据帧中一列的元素添加到另一个数据帧中另一列的元素,python-3.x,pandas,dataframe,Python 3.x,Pandas,Dataframe,嗨,我有以下数据帧 我想将Df2中M/O列的元素添加到Df1中A/O列的元素中。Df2 M/L到Df1 A/L的情况也是如此 这两个数据帧的列名都有两个级别 我正在尝试以下操作,但它没有将Df2的第5行添加到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.Data

嗨,我有以下数据帧

我想将Df2中M/O列的元素添加到Df1中A/O列的元素中。Df2 M/L到Df1 A/L的情况也是如此

这两个数据帧的列名都有两个级别

我正在尝试以下操作,但它没有将Df2的第5行添加到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)
你知道为什么吗

谢谢,您可以将drop_level=False用于返回多索引数据帧,然后将top level重命名为与Df1的级别A对齐:


是否可以将图片转换为文本以复制数据?@Thanasis df1和df2@panda不,没有,但是,即使有,也能让它工作。@jezrael,我已经添加了这些表作为代码。@Thanasis-谢谢。是否需要最后2个值NaN?G列必须与Df1相同
df = Df2.xs('M', axis=1, level=0, drop_level=False).rename(columns={'M':'A'}, level=0)
Df1 = Df1.add(df, fill_value=0)
print (Df1)
      A          G     
      L     O    L    O
1  14.0   6.0  3.0  2.0
2  16.0   8.0  3.0  2.0
3  18.0  10.0  3.0  2.0
4  12.0   8.0  3.0  2.0
5   8.0   4.0  NaN  NaN