创建一个基于其他两个系列的新系列

问题描述 投票:2回答:2

我是python的新手。关于如何从其他两个系列中获得新系列有一个问题。例如

a  b 
1  6 
4  7
5  8
8  9

那么如果a是奇数,则b * 2和a是偶数* 3,之后我们想得到一个新系列。

c
1 is odd ? 6 * 2 : 6 * 3
4 is odd ? 7 * 2 : 7 * 3
5 is odd ? 8 * 2 : 8 * 3
8 is odd ? 9 * 2 : 9 * 3

=======>

c
12
21
16
27
python pandas series
2个回答
6
投票

看马云,没有经营者:

df['a'].mod(2).rsub(3).mul(df['b'])

0    12
1    21
2    16
3    27
dtype: int64

您也可以使用np.where来获取被乘数,而不是在表达式内乘以。这样你只需要在结尾乘以一次(乘法很贵!):

df['b'] * np.where(df['a'] % 2, 2, 3)

0    12
1    21
2    16
3    27
Name: b, dtype: int64

3
投票

这是你需要np.where%

The % (modulo) operator yields the remainder from the division of the
first argument by the second
np.where(df.a%2,df.b*2,df.b*3)
Out[1115]: array([12, 21, 16, 27], dtype=int64)
df['c']= np.where(df.a%2,df.b*2,df.b*3)

嗯,也许使用十进制隐藏二进制

(-df.a.map(bin).str[-1].astype(int)+3)*df.b
Out[1125]: 
0    12
1    21
2    16
3    27
dtype: int64
© www.soinside.com 2019 - 2024. All rights reserved.