PySpark - 从 Numpy 矩阵创建数据帧 [英] PySpark - Create DataFrame from Numpy Matrix

查看:29
本文介绍了PySpark - 从 Numpy 矩阵创建数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 numpy 矩阵:

I have a numpy matrix:

arr = np.array([[2,3], [2,8], [2,3],[4,5]])

我需要从 arr 创建一个 PySpark 数据帧.我无法手动输入值,因为 arr 的长度/值会动态变化,所以我需要将 arr 转换为数据帧.

I need to create a PySpark Dataframe from arr. I can not manually input the values because the length/values of arr will be changing dynamically so I need to convert arr into a dataframe.

我尝试了以下代码但没有成功.

I tried the following code to no success.

df= sqlContext.createDataFrame(arr,["A", "B"])

但是,我收到以下错误.

However, I get the following error.

TypeError: Can not infer schema for type: <type 'numpy.ndarray'>

推荐答案

希望对您有所帮助!

import numpy as np

#sample data
arr = np.array([[2,3], [2,8], [2,3],[4,5]])

rdd1 = sc.parallelize(arr)
rdd2 = rdd1.map(lambda x: [int(i) for i in x])
df = rdd2.toDF(["A", "B"])
df.show()

输出为:

+---+---+
|  A|  B|
+---+---+
|  2|  3|
|  2|  8|
|  2|  3|
|  4|  5|
+---+---+

这篇关于PySpark - 从 Numpy 矩阵创建数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆