繁体   English   中英

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

[英]populate new column in a pandas dataframe which takes input from other columns

我有一个函数,它应该将 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

取决于您的功能有多复杂。 一般来说,您可以使用pandas.DataFrame.apply

>>> 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

axis=1是让你的函数“为每一行”而不是“为每一列”工作:

传递给函数的对象是具有索引 DataFrame 的索引 (axis=0) 或列 (axis=1) 的 Series 对象

但是如果它真的是简单的函数,就像上面的那个,你甚至可以不用函数,用向量化操作来做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM