我正在尝试提高使用Java在Spark中实现的Logistic回归算法的准确性.为此,我试图用该列的最频繁值替换列中存在的Null或无效值.例如:-
Name|Place
a   |a1
a   |a2
a   |a2
    |d1
b   |a2
c   |a2
c   |
    |
d   |c1
在这种情况下,我将"Name"列中的所有NULL值替换为"a",将"Place"替换为"a2"列.到目前为止,我只能提取特定列中最常见的列.关于如何用该列的最常用值替换空值或无效值,能否帮助我完成第二步.
我在不可为空的数据框中有一个 StructField。简单的例子:
import pyspark.sql.functions as F
from pyspark.sql.types import *
l = [('Alice', 1)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df = df.withColumn('foo', F.when(df['name'].isNull(),False).otherwise(True))
df.schema.fields
返回:
[StructField(name,StringType,true), StructField(age,LongType,true), StructField(foo,BooleanType,false)]
请注意,该字段foo不可为空。问题是(出于我不会讨论的原因)我希望它可以为空。我发现这篇文章Change nullable property of column in spark dataframe建议了一种方法,所以我将其中的代码调整为:
import pyspark.sql.functions as F
from pyspark.sql.types import *
l = [('Alice', 1)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df = df.withColumn('foo', F.when(df['name'].isNull(),False).otherwise(True))
df.schema.fields
newSchema = [StructField('name',StringType(),True), StructField('age',LongType(),True),StructField('foo',BooleanType(),False)]
df2 = sqlContext.createDataFrame(df.rdd, newSchema)
失败了:
TypeError: StructField(name,StringType,true) 不是 JSON 可序列化的
我也在堆栈跟踪中看到了这一点:
raise ValueError("检测到循环引用")
所以我有点卡住了。任何人都可以修改这个例子,使我能够定义一个列可以 …