Skip to main content
 首页 » 编程设计

python之如何将 unicode 转换为数据框列的字符串

2024年12月31日23Free-Thinker

我有一个 spark 数据框,其中有一列“X”。该列包含以下形式的元素:

u'[23,4,77,890,455,................]'

.如何将此 unicode 转换为列表。我的输出应该是

[23,4,77,890,455...................]

.我已将它应用于“X”列中的每个元素。

我试过 df.withColumn("X_new", ast.literal_eval(x)) 并得到错误

"Malformed String"

我也试过

df.withColumn("X_new", json.loads(x)) and got the error "Expected String or Buffer"

和

df.withColumn("X_new", json.dumps(x)) which says JSON not serialisable.

还有

df_2 = df.rdd.map(lambda x: x.encode('utf-8')) which says rdd has no attribute encode.

我不想使用 collect 和 toPandas(),因为它会消耗内存。(但如果这是唯一的方法,请告诉我)。我正在使用 Pyspark

更新:cph_sto 使用 UDF 给出了答案。虽然它运行良好,但我发现它很慢。有人可以建议任何其他方法吗?

请您参考如下方法:

import ast 
from pyspark.sql.functions import udf 
values = [(u'[23,4,77,890.455]',10),(u'[11,2,50,1.11]',20),(u'[10.05,1,22.04]',30)] 
df = sqlContext.createDataFrame(values,['list','A']) 
df.show() 
+-----------------+---+ 
|             list|  A| 
+-----------------+---+ 
|[23,4,77,890.455]| 10| 
|   [11,2,50,1.11]| 20| 
|  [10.05,1,22.04]| 30| 
+-----------------+---+     
 
# Creating a UDF to convert the string list to proper list 
string_list_to_list = udf(lambda row: ast.literal_eval(row)) 
df = df.withColumn('list',string_list_to_list(col('list'))) 
df.show() 
+--------------------+---+ 
|                list|  A| 
+--------------------+---+ 
|[23, 4, 77, 890.455]| 10| 
|   [11, 2, 50, 1.11]| 20| 
|   [10.05, 1, 22.04]| 30| 
+--------------------+---+ 

Q 的扩展,按照 OP 的要求 -

# Creating a UDF to find length of resulting list. 
length_list = udf(lambda row: len(row)) 
df = df.withColumn('length_list',length_list(col('list'))) 
df.show() 
+--------------------+---+-----------+ 
|                list|  A|length_list| 
+--------------------+---+-----------+ 
|[23, 4, 77, 890.455]| 10|          4| 
|   [11, 2, 50, 1.11]| 20|          4| 
|   [10.05, 1, 22.04]| 30|          3| 
+--------------------+---+-----------+