python - if 条件在行和列中递归

标签 python pandas python-2.7 apply

在 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用于对 df1df2

中的所有值进行广播比较 <小时/>
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/

相关文章:

python - 在 Python 中进行优化的冒泡排序

python - 管理自定义对象到额外日期和时间的最佳方法

python - 在大文件上使用 Pandas 数据透视表的最有效方法

python - 只需要需求文件中的两个依赖项之一

python - 将 AWS 凭证传递给 Google Cloud Dataflow,Python

python:无法解释的无限递归与__repr__

python - 如何在按某些条件查询后更改 pandas DataFrame 值

python - 无法使用 openpyxl 加载工作簿

python - 如何修复重新声明的警告?

python - mysql表中的"where"