将NumPy数组的DataFrame转换为Spark DataFrame。

3

我有一个pandas DataFrame,它由一个整数列和一个numpy数组列组成

DataFrame({'col_1':[1434,3046,3249,3258], 'col_2':[np.array([1434, 1451, 1467]),np.array([3046, 3304]),
    np.array([3249, 3246, 3298, 3299, 3220]),np.array([3258, 3263, 3307])]})


   col_1    col_2
0   1434    [1434, 1451, 1467]
1   3046    [3046, 3304]
2   3249    [3249, 3246, 3298, 3299, 3220]
3   3258    [3258, 3263, 3307]

我想将以下格式的数据转化为Spark DataFrame:
df=sc.parallelize([  [1434,[1434, 1451, 1467]],
          [3046,[3046, 3304]],
          [3249,[3046, 3304]],
          [3258,[3258, 3263, 3307]]]).toDF(['col_1','col_2'])


df.select('col_1',explode(col('col_2')).alias('col_2')).show(14)


+-----+-----+
|col_1|col_2|
+-----+-----+
| 1434| 1434|
| 1434| 1451|
| 1434| 1467|
| 3046| 3046|
| 3046| 3304|
| 3249| 3046|
| 3249| 3304|
| 3258| 3258|
| 3258| 3263|
| 3258| 3307|
+-----+-----+

如果我试图直接将Pandas DataFrame 转换为 Spark DataFrame,会出现错误。

not supported type: <type 'numpy.ndarray'>
1个回答

6
我想一种方法是将DataFrame中的每一行转换为整数列表。
df.col_2 = df.col_2.map(lambda x: [int(e) for e in x])

然后,直接将其转换为Spark DataFrame

df_spark = spark.createDataFrame(df)
df_spark.select('col_1', explode(col('col_2')).alias('col_2')).show(14)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接