在 2 个不同数据帧的行和列中应用 if 条件时出现问题。
df1
X1 X2 X3 X4 X5
10 12 8 4 6
df2
class MARKS
class_1 8
class_2 6
class_3 9
class_4 10
class_5 11
class_6 8
class_7 5
class_8 4
class_9 7
class_10 5
预期输出:
class 1 Y Y FALSE FALSE FALSE
class 2 Y Y Y FALSE FALSE
class 3 Y Y FALSE FALSE FALSE
class 4 FALSE Y FALSE FALSE FALSE
class 5 FALSE Y FALSE FALSE FALSE
class 6 Y Y FALSE FALSE FALSE
class 7 Y Y Y FALSE Y
class 8 Y Y Y FALSE Y
class 9 Y Y Y FALSE FALSE
class 10 Y Y Y FALSE Y
formula: =IF($A$2>$I2,"Y")
FOR CLASS 1 - I2 WILL BE CONSTANT
例如:其中 A2 = df1 的 10,I2 = df2 的 8。如果 10 > 8 则打印 Y,否则条件失败并打印 FALSE。
FOR CLASS 2 - I3 WILL BE CONSTANT
FORMULA =IF($A$2>$I3,"Y")
类似,其中 B2 = 12 OF DF1 AND I3 = 6 OF df2,因此如果 12>6 则打印 Y,否则条件失败并打印 FALSE。
code i tried:
df1 = pd.read_csv("df1.csv")
df2 = pd.read_csv("df2.csv")
y = df2.MARKS
Res = apply(data[3,],2,function(x)
if x <= y:
print("FALSE")
else:
print("Y")
Res
ERROR:
File "<ipython-input-27-083bd28bed08>", line 2
if x <= y:
^
SyntaxError: invalid syntax
请帮忙。
最佳答案
使用np.less.outer
用于对 df1
与 df2
a = df1.values.ravel()
b = df2.MARKS.values
pd.DataFrame(np.where(np.less.outer(b, a), 'Y', 'FALSE'), index=df2['class'])
# If you don't really want 'Y' and 'FALSE', replace those values with what you do want
0 1 2 3 4
class
class_1 Y Y FALSE FALSE FALSE
class_2 Y Y Y FALSE FALSE
class_3 Y Y FALSE FALSE FALSE
class_4 FALSE Y FALSE FALSE FALSE
class_5 FALSE Y FALSE FALSE FALSE
class_6 Y Y FALSE FALSE FALSE
class_7 Y Y Y FALSE Y
class_8 Y Y Y FALSE Y
class_9 Y Y Y FALSE FALSE
class_10 Y Y Y FALSE Y
关于python - if 条件在行和列中递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56633825/