在Pandas中将奇数转换为布尔值

时间:2018-01-15 11:24:54

标签: python pandas numpy

我想在pandas中转换一个列:

A 
1
2
3
4

到另一个将奇数转换为布尔值的列:

A is_odd
1 True
2 False
3 True
4 False

我正在考虑使用这段不起作用的代码:

data["is_odd"] = not(bool(data["A"].mod(2)))

有什么想法吗?

1 个答案:

答案 0 :(得分:5)

df['is_odd'] = df['A'] % 2 == 1
print (df)
   A  is_odd
0  1    True
1  2   False
2  3    True
3  4   False

来自@cᴏʟᴅsᴘᴇᴇᴅ的类似解决方案:

df['is_odd'] = df['A'].mod(2).astype(bool)

或者:

df['is_odd'] = (df['A'] & 1).astype(bool)