使用筛选功能时如何填充所有列?
how fill all columns when I use filter function?
我有很多具有真值和假值的列。如果 2 列为真,我想创建一个值为 1 的新列,否则为 0。
col1 col2 col3
true false true
true true true
false true false
输出:如果 col1 和 col2 为真,则过滤数据:df.filter((df.col(col1)==true) & (df.col(col2)==true))
col1 col2 col3 R
true false true 0
true true false 1
false true false 0
如果你的 df 中的 true/false 是字符串,你没有明确说明。不管怎样,高阶函数应该会让你的生活更轻松。
如果 df 中的 true/false 值是字符串,请从这里开始
df=reduce(lambda df,c: df.withColumn(c, df[c].cast('boolean')), df.columns, df)
解决方案
df =(df.withColumn('R', array([c for c in df.columns]))#Array all the columns
#First transform the booleans into integers
#Follow that by adding the integers in the array
#Check if the result above is more than two. That will give you a boolean
#Cast the boolean to integer
.withColumn('R',expr("cast (reduce(transform(R,x->cast(x as integer)),0,(c,i)->c+i)>2 as integer)"))
).show()
+-----+-----+-----+---+
| col1| col2| col3| R|
+-----+-----+-----+---+
| true|false| true| 0|
| true| true| true| 1|
|false| true|false| 0|
+-----+-----+-----+---+
我有很多具有真值和假值的列。如果 2 列为真,我想创建一个值为 1 的新列,否则为 0。
col1 col2 col3
true false true
true true true
false true false
输出:如果 col1 和 col2 为真,则过滤数据:df.filter((df.col(col1)==true) & (df.col(col2)==true))
col1 col2 col3 R
true false true 0
true true false 1
false true false 0
如果你的 df 中的 true/false 是字符串,你没有明确说明。不管怎样,高阶函数应该会让你的生活更轻松。
如果 df 中的 true/false 值是字符串,请从这里开始
df=reduce(lambda df,c: df.withColumn(c, df[c].cast('boolean')), df.columns, df)
解决方案
df =(df.withColumn('R', array([c for c in df.columns]))#Array all the columns
#First transform the booleans into integers
#Follow that by adding the integers in the array
#Check if the result above is more than two. That will give you a boolean
#Cast the boolean to integer
.withColumn('R',expr("cast (reduce(transform(R,x->cast(x as integer)),0,(c,i)->c+i)>2 as integer)"))
).show()
+-----+-----+-----+---+
| col1| col2| col3| R|
+-----+-----+-----+---+
| true|false| true| 0|
| true| true| true| 1|
|false| true|false| 0|
+-----+-----+-----+---+