我的数据帧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
您可以要求所有值都满足条件。
df = pd.DataFrame([[0,0,0],[0,0,1], [0,1,0], [0,0,0]], columns=['A', 'B', 'C'])
df['Output'] = df.eq(False).all(1).astype(int)
df
Out[1]:
A B C Output
0 0 0 0 0
1 0 0 1 1
2 0 1 0 1
3 0 0 0 0