Python 在从其他列获取输入的数据框中填充新列

Python 在从其他列获取输入的数据框中填充新列,python,pandas,Python,Pandas,我有一个函数,它应该以x,y,z作为输入,并返回r作为输出。 例如:my_func(x,y,z)取x=10,y='apple'和z=2,并在列r中返回值。类似地,函数接受x=20、y=orange和z=4,并填充列r中的值。有什么建议这方面的有效代码是什么 之前: a x y z 5 10 'apple' 2 2 20 'orange' 4 0 4 'apple' 2 5 5 'pea

我有一个函数,它应该以x,y,z作为输入,并返回r作为输出。 例如:my_func(x,y,z)取x=10,y='apple'和z=2,并在列r中返回值。类似地,函数接受x=20、y=orange和z=4,并填充列r中的值。有什么建议这方面的有效代码是什么

之前:

   a  x       y       z      
   5  10   'apple'    2
   2  20   'orange'   4
   0  4    'apple'    2
   5  5    'pear'     6
之后:

   a  x       y       z      r
   5  10   'apple'    2      x
   2  20   'orange'   4      x
   10  4   'apple'    2      x
   5  5    'pear'     6      x

取决于函数的复杂程度。通常,您可以使用:

axis=1
是让函数“针对每行”而不是“针对每列”工作:

传递给函数的对象是具有以下索引的系列对象: 数据帧的索引(轴=0)或列(轴=1)

但是如果它真的是一个简单的函数,就像上面的一样,你甚至可以不用函数,通过向量化操作来完成它

>>> def my_func(x):
...     return '{0} - {1} - {2}'.format(x['y'],x['a'],x['x'])
... 
>>> df['r'] = df.apply(my_func, axis=1)
>>> df
   a   x         y  z                  r
0  5  10   'apple'  2   'apple' - 5 - 10
1  2  20  'orange'  4  'orange' - 2 - 20
2  0   4   'apple'  2    'apple' - 0 - 4
3  5   5    'pear'  6     'pear' - 5 - 5