关于火花的大多数问题都用show
作为代码示例,而没有生成数据框的代码,例如:
df.show()
+-------+--------+----------+
|USER_ID|location| timestamp|
+-------+--------+----------+
| 1| 1001|1265397099|
| 1| 6022|1275846679|
| 1| 1041|1265368299|
+-------+--------+----------+
如何在编程环境中重现此代码而无需手动重写? pyspark在熊猫中有read_clipboard
的等效值吗?
缺少将数据导入我的环境的功能,这对我帮助他人在Stackoverflow中使用pyspark构成了很大的障碍。
所以我的问题是:
最简单的方法是将show
命令中粘贴在stackoverflow中的数据复制到我的环境中?
答案 0 :(得分:2)
您始终可以使用以下功能:
from pyspark.sql.functions import *
def read_spark_output(file_path):
step1 = spark.read \
.option("header","true") \
.option("inferSchema","true") \
.option("delimiter","|") \
.option("parserLib","UNIVOCITY") \
.option("ignoreLeadingWhiteSpace","true") \
.option("ignoreTrailingWhiteSpace","true") \
.option("comment","+") \
.csv("file://{}".format(file_path))
# select not-null columns
step2 = t.select([c for c in t.columns if not c.startswith("_")])
# deal with 'null' string in column
return step2.select(*[when(~col(col_name).eqNullSafe("null"), col(col_name)).alias(col_name) for col_name in step2.columns])
这是以下问题中给出的建议之一: How to make good reproducible Apache Spark examples 。
注释1:有时,在某些特殊情况下,由于某些原因或其他原因,这可能不适用,并且可能产生错误/问题,即Group by column "grp" and compress DataFrame - (take last not null value for each column ordering by column "ord")。 所以请谨慎使用!
注释2 :(免责声明),我不是代码的原始作者。感谢@MaxU提供的代码。我刚刚对其做了一些修改。
答案 1 :(得分:2)
最新答案,但是我经常遇到同样的问题,因此为此https://github.com/ollik1/spark-clipboard
写了一个小实用程序它基本上允许复制粘贴的数据帧显示字符串闪烁。要安装它,请添加jcenter依赖项com.github.ollik1:spark-clipboard_2.12:0.1
和spark config .config("fs.clipboard.impl", "com.github.ollik1.clipboard.ClipboardFileSystem")
之后,可以直接从系统剪贴板读取数据帧
val df = spark.read
.format("com.github.ollik1.clipboard")
.load("clipboard:///*")
,或者根据需要选择归档。自述文件中描述了安装细节和用法。
答案 2 :(得分:1)
您始终可以将pandas中的数据作为pandas数据框读取,然后将其转换回spark数据框。不,与熊猫不同,pyspark中没有read_clipboard的直接等效项。
原因是Pandas数据帧大多是平面结构,因为Spark数据帧可以具有诸如struct,array等复杂结构,因为它具有各种各样的数据类型,并且这些数据类型不会出现在控制台输出中,所以这是不可能的从输出重新创建数据框。
答案 3 :(得分:0)
您可以结合使用熊猫read_clipboard,并转换为pyspark数据框
from pyspark.sql.types import *
pdDF = pd.read_clipboard(sep=',',
index_col=0,
names=['USER_ID',
'location',
'timestamp',
])
mySchema = StructType([ StructField("USER_ID", StringType(), True)\
,StructField("location", LongType(), True)\
,StructField("timestamp", LongType(), True)])
#note: True (implies nullable allowed)
df = spark.createDataFrame(pdDF,schema=mySchema)
更新:
@terry真正想要的是将ASCII代码表复制到python,以下是 例。当您将数据解析为python时,便可以转换为任何内容。
def parse(ascii_table):
header = []
data = []
for line in filter(None, ascii_table.split('\n')):
if '-+-' in line:
continue
if not header:
header = filter(lambda x: x!='|', line.split())
continue
data.append(['']*len(header))
splitted_line = filter(lambda x: x!='|', line.split())
for i in range(len(splitted_line)):
data[-1][i]=splitted_line[i]
return header, data