Pyspark:从pyspark数据框中
删除UTF空字符我有类似如下的pyspark数据帧:Pyspark:从pyspark数据框中
df = sql_context.createDataFrame([
Row(a=3, b=[4,5,6],c=[10,11,12], d='bar', e='utf friendly'),
Row(a=2, b=[1,2,3],c=[7,8,9], d='foo', e=u'ab\u0000the')
])
凡e
列中的值中的一个包含UTF空字符\u0000
。如果我尝试这个df
加载到PostgreSQL数据库中,我得到以下错误:
ERROR: invalid byte sequence for encoding "UTF8": 0x00
这是有道理的。在将数据加载到postgres之前,如何有效地从pyspark数据框中删除空字符?
我尝试过使用一些pyspark.sql.functions
先清除数据,但没有成功。 encode
,decode
和regex_replace
没有工作:
df.select(regexp_replace(col('e'), u'\u0000', ''))
df.select(encode(col('e'), 'UTF-8'))
df.select(decode(col('e'), 'UTF-8'))
理想情况下,我想清洁整个数据帧没有确切指明哪些列或违规性质是什么,因为我没有必要提前知道这个信息时间。
我正在使用postgres 9.4.9数据库与UTF8
编码。
等待 - 我想我已经拥有了。如果我做这样的事情,似乎工作:
null = u'\u0000'
new_df = df.withColumn('e', regexp_replace(df['e'], null, ''))
然后映射到所有的字符串列:
string_columns = ['d','e']
new_df = df.select(
*(regexp_replace(col(c), null, '').alias(c) if c in string_columns else c for
c in df.columns)
)
您可以使用DataFrame.fillna()
更换空值。
Replace null values, alias for na.fill(). DataFrame.fillna() and DataFrameNaFunctions.fill() are aliases of each other.
Parameters:
value – int, long, float, string, or dict. Value to replace null values with. If the value is a dict, then subset is ignored and value must be a mapping from column name (string) to replacement value. The replacement value must be an int, long, float, or string.
subset – optional list of column names to consider. Columns specified in subset that do not have matching data type are ignored. For example, if value is a string, and subset contains a non-string column, then the non-string column is simply ignored.
我不认为这在这里工作,因为问题单元格实际上不是空 - 它包含UTF空字符\ u0000。如果我在我的示例df上运行'df.fillna()',它看起来像返回相同的数据帧,因为没有任何单元实际为空。如果我尝试将生成的df加载到postgres表中,我仍然会得到相同的错误消息。 – Steve