pandas - 并且对于熊猫中布尔和非布尔列的声明令人惊讶地产生了结果
问题描述
我在 pandas DataFrame 中“与”一个二进制和非二进制列。令我惊讶的是,这实际上给出了一个结果(我期待一个错误)。看看下面的代码:
import pandas as pd
d = {'col1':[1,1,2,2,2], 'col2':[3,4,4,4,3]}
test_df = pd.DataFrame(data = d)
test_df['bool1'] = [True, False, True, True, False]
test_df['bool2'] = [True, False, True, True, True]
test_df['col3'] = [1,3,3,5,5]
test_df['col3'] & test_df['bool1']
我得到以下结果:
0 True
1 False
2 True
3 True
4 False
dtype: bool
熊猫如何评价这个?col3
不是布尔值/二进制,所以我很难确定是什么决定了两者的组合是True
还是False
?
解决方案
这里被转换0
为False
和另一个整数到True
s:
d = {'col1':[1,1,2,2,2], 'col2':[3,4,4,4,3]}
test_df = pd.DataFrame(data = d)
test_df['bool1'] = [True, False, True, True, False]
test_df['bool2'] = [True, False, True, True, True]
#changed first value to 0
test_df['col3'] = [0,3,3,5,5]
print (test_df['col3'] & test_df['bool1'])
0 False
1 False
2 True
3 True
4 False
dtype: bool
它的工作方式类似于astype
:
print (test_df['col3'].astype(bool))
0 False
1 True
2 True
3 True
4 True
Name: col3, dtype: bool
推荐阅读
- sql-server - tempdb 和数据库事务日志都已满
- reactjs - 无法在 ReactJS 状态内渲染数组
- android - Android studio C++ ndk 摄像头
- python-3.x - Pyomo 不能使用 gurobi 求解器
- node.js - 语义发布无法发布到 npm
- android - Tablayout 旁边的导航抽屉按钮
- javascript - 通过 JSON 数组进行索引
- android - BottomNavigationView 的等间距菜单项
- html - How can I horizontally center an svg grouped circle (two paths)?
- apache-spark - Oozie Spark Action (Containing HiveContext) Giving java.lang.OutOfMemoryError: PermGen space