python-3.x - 处理“\000”、“\n”、“\r”、“bellchars”等特殊字符;在 pyspark 数据框中
问题描述
我有以下python数据框:
d = [{'name': ' Alice', 'age': "1 '' 2"}, {'name': ' " ', 'age': "â"}, {'name': '', 'age': "ây"}, {'name': '', 'age': "null"}]
我已经解决了空间问题,但我还想删除数据框中的任何特殊字符,如“\000”、“\n”、“\r”、“bellchars”。
我尝试了以下代码来处理特殊字符:
for col_i in df_test.columns:
df_ascii = df_test.withColumn(col_i, unidecode(unicode(col_i, encoding = "utf-8")))
我还使用了以下代码:
def nonasciitoascii(unicodestring):
return unicodestring.encode("ascii","ignore")
convertedudf = udf(nonasciitoascii)
for cols in df_test.columns:
print(cols)
converted = df_test.withColumn(cols,convertedudf(df_test[cols]))
但输出是:
有没有办法让我解决这个问题?我尝试了一些其他代码示例,但无法处理上述字符(通过处理我的意思是删除)。
解决方案
尝试pyspark.sql.function.regexp_replace
相同。
df = sqlContext.createDataFrame(
[{'name': ' Alice', 'age': "1 '' 2"},
{'name': ' " ', 'age': "â"},
{'name': '', 'age': "ây"},
{'name': '', 'age': "null"}])
df.select([
F.regexp_replace(col, '[(\n)(\r)(\000)( )]', "").alias(col)
for col in df.columns]).collect()
输出:
[Row(age="1''2", name='Alice'),
Row(age='â', name='"'),
Row(age='ây', name=''),
Row(age='null', name='')]
如何删除所有非字母数字字符?
df = sqlContext.createDataFrame(
[{'name': ' Ali.|ce', 'age': "1 '' 2"},
{'name': ' " ', 'age': "â"},
{'name': '', 'age': "ây"},
{'name': '', 'age': "null"}])
# This expression will keep all the alphanumeric values
# plus whatever special symbol we would like to keep
# ex '.' and '|' are kept in this example.
df.select([
F.regexp_replace(col, '[^(\w)+(.|)]', "").alias(col)
for col in df.columns]).collect()
输出:
[Row(age='12', name='Ali.|ce'),
Row(age='', name=''),
Row(age='y', name=''),
Row(age='null', name='')]
推荐阅读
- python - aubio.notes 工作不正确(Python)
- c++ - 关于带有编译错误的操作列表的问题
- kubernetes - Kubernetes Ingress 在路由之前执行授权,例如 api gateway
- android - 为什么 gson 认为我的 json 提要是一个对象,而它显然是一个数组?
- c - C:在同一表达式中使用少量 pow 函数时结果无效
- python - 如何在函数中正确使用列表以适用于所有输入
- javascript - Firestore where 不等式子句
- r - 使用 dplyr 过滤掉向量中重复文件的两个副本
- qt - 从片段组装 QTextDocument
- python - 更改 Python 函数调用字体颜色