Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.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 基于另一个数据帧的行值对一个数据帧中的列求和_Python_Pandas_Dataframe - Fatal编程技术网

Python 基于另一个数据帧的行值对一个数据帧中的列求和

Python 基于另一个数据帧的行值对一个数据帧中的列求和,python,pandas,dataframe,Python,Pandas,Dataframe,比如说,我有一个数据帧df: a b c d e 0 1 2 dd 5 Col1 1 2 3 ee 9 Col2 2 3 4 ff 1 Col4 还有另一个数据帧df2: Col1 Col2 Col3 0 1 2 4 1 2 3 5 2 3 4 6 我需要在第一个数据帧中添加一个列和,其中它根据df1中列e的值对第二个数据帧df2中

比如说,我有一个数据帧df:

   a  b   c  d   e
0  1  2  dd  5  Col1
1  2  3  ee  9  Col2
2  3  4  ff  1  Col4
还有另一个数据帧df2:

  Col1   Col2   Col3 
0  1      2       4      
1  2      3       5      
2  3      4       6  
我需要在第一个数据帧中添加一个列和,其中它根据df1中列e的值对第二个数据帧df2中列的值求和

预期产量

   a  b   c  d   e     Sum
0  1  2  dd  5  Col1    6
1  2  3  ee  9  Col2    9
2  3  4  ff  1  Col4    0
最后一行中的和值为0,因为df2中不存在Col4

我尝试的是:编写一些lamda,应用函数。我没能做到。 我非常感谢你的帮助。谢谢。

试试看

df['Sum']=df.e.map(df2.sum()).fillna(0)
df
Out[89]: 
   a  b   c  d     e  Sum
0  1  2  dd  5  Col1  6.0
1  2  3  ee  9  Col2  9.0
2  3  4  ff  1  Col4  0.0
试一试


试试这个。以下解决方案使用apply方法对df2中存在的特定列的所有值求和,如果df2中不存在此类列,则返回0


试试这个。以下解决方案使用apply方法对df2中存在的特定列的所有值求和,如果df2中不存在此类列,则返回0

使用.iterrows在数据帧中进行迭代,提取每行的值和索引

循环嵌套风格的迭代可用于从第二个数据帧获取所需的值,并将其应用于第一个数据帧

import pandas as pd

df1 = pd.DataFrame(data={'a': [1,2,3], 'b': [2,3,4], 'c': ['dd', 'ee', 'ff'], 'd': [5,9,1], 'e': ['Col1','Col2','Col3']})
df2 = pd.DataFrame(data={'Col1': [1,2,3], 'Col2': [2,3,4], 'Col3': [4,5,6]})
df1['Sum'] = df1['a'].apply(lambda x: None)


for index, value in df1.iterrows():
  sum = 0
  for index2, value2 in df2.iterrows():
    sum += value2[value['e']]
    
  df1['Sum'][index] = sum
输出:

    a   b   c   d   e       Sum
0   1   2   dd  5   Col1    6
1   2   3   ee  9   Col2    9
2   3   4   ff  1   Col3    15
使用.iterrows在数据帧中进行迭代,提取每行的值和索引

循环嵌套风格的迭代可用于从第二个数据帧获取所需的值,并将其应用于第一个数据帧

import pandas as pd

df1 = pd.DataFrame(data={'a': [1,2,3], 'b': [2,3,4], 'c': ['dd', 'ee', 'ff'], 'd': [5,9,1], 'e': ['Col1','Col2','Col3']})
df2 = pd.DataFrame(data={'Col1': [1,2,3], 'Col2': [2,3,4], 'Col3': [4,5,6]})
df1['Sum'] = df1['a'].apply(lambda x: None)


for index, value in df1.iterrows():
  sum = 0
  for index2, value2 in df2.iterrows():
    sum += value2[value['e']]
    
  df1['Sum'][index] = sum
输出:

    a   b   c   d   e       Sum
0   1   2   dd  5   Col1    6
1   2   3   ee  9   Col2    9
2   3   4   ff  1   Col3    15