python - 如何使用 Pandas 构建三个输入或门
问题描述
我的数据帧 df 有 3 个输入(A、B、C),如下所示
A B C
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
我想要构建逻辑或门并具有如下所示的示例输出
A B C Output
0 0 0 0
0 0 1 1
0 1 0 1
0 1 1 1
1 0 0 1
1 0 1 1
1 1 0 1
1 1 1 1
如何在熊猫中做到这一点
解决方案
您只需要评估df.A | df.B | df.C
.
df['OR_Gate'] = df.A | df.B | df.C
注意:如果 A、B、C 列中的值是 0 和 1 的字符串,则执行以下操作之一:
# Method-1:
# Convert the strings into int and then evaluate OR_Gate:
# This changes the value-types in the columns A, B, C
df = df.astype('int')
df['OR_Gate'] = df.A | df.B | df.C
# Method-2:
# This will not change the original data type in columns A, B, C
# But will correctly evaluate 'OR_Gate'.
df['OR_Gate'] = df.A.astype(int) | df.B.astype(int) | df.C.astype(int)
# Method-3:
# If you want your final output to be in boolean form.
df['OR_Gate'] = df.A.astype(bool) | df.B.astype(bool) | df.C.astype(bool)
详细解决方案
import pandas as pd
# Dummy data
A = [0]*4 + [1]*4
B = [0]*2 + [1]*2 + [0]*2 + [1]*2
C = [0, 1]*4
# Make Dataframe
df = pd.DataFrame({'A': A, 'B': B, 'C': C})
# Update 'OR_Gate' Output
df['OR_Gate'] = df.A | df.B | df.C
df
输出:
A B C OR_Gate
0 0 0 0 0
1 0 0 1 1
2 0 1 0 1
3 0 1 1 1
4 1 0 0 1
5 1 0 1 1
6 1 1 0 1
7 1 1 1 1
推荐阅读
- windows - 带有 Powershell Send-MailMessage 的 Windows 批处理 - 一半的换行符未显示
- php - 从数组中获取重复的下一个值的计数并将其存储到其他数组
- csv - 如何在 Neo4j 中从外部网站导入 csv?
- amazon-web-services - 如何从 EventBridge 定位 http api 网关或 ALB
- ios - 目标 C 显示最近的问题未定义的符号:_OBJC_CLASS_$_FIRApp
- excel - 如何在excel vba中将范围分配给命名范围?
- java - 普通类和注入类的区别
- python-3.x - 当我尝试在 Google Collab 中克隆 github 存储库时,为什么会收到“错误:命令错误,退出状态为 1”?
- reactjs - 为什么 react-image-magnify 在 swiper js 中不起作用?
- javascript - 多个动态输入 onchange 和 onblur 函数 javascript