我是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
看马云,没有经营者:
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
这是你需要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