[英]Apply a function using another array how a argument in a pandas.Series
有什么方法可以使用另一个pandas.Series
的不同值在 pandas.Series 中应用pandas.Series
吗? 我知道有pandas.Series.apply()
,但我需要这样的东西:
array1 = pandas.Series([1, 2, 3, 4])
array2 = pandas.Series([5, 5, 6, 0])
def func(x, y):
return x+y
print(array1.apply(func, args = array2))
Out:
0 6
1 7
2 9
3 4
In other words, I need apply a function in a pandas.DataFrame
column by I need use another column of same pandas.DataFrame
. 使用相同的 function func
:
df = pandas.DataFrame({'a': [1, 2, 3, 4], 'b': [5, 5, 6, 0]})
df['c'] = df['a'].apply(func, args = df['b'])
print(df)
Out:
a b c
0 1 5 6
1 2 5 7
2 3 6 9
3 4 0 4
谢谢!
我需要使用apply,因为我使用像pandarallel这样的多处理,所以我只需将apply()更改为parallel_apply(),有人知道怎么做吗? 将多处理与使用两列的操作一起使用?
如果你想从两个数据框中添加列,那么而不是
print(array1.apply(func, args = array2))
您可以使用
print(func(array1, array2))
0 6
1 7
2 9
3 4
如果要添加两列相同的dataframe,可以通过以下方式简单地进行:
df['c'] = func(df['a'], df['b'])
print(df)
...:
a b c
0 1 5 6
1 2 5 7
2 3 6 9
3 4 0 4
对于特定情况,您可以使用:
df['c'] = df['a'] + df['c']
对于主要的 function,您使用Numpy
就像在这个例子中一样
df['c'] = numpy.exp(df['a']) + df['b']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.