【问题标题】:Return data from same row as a given query in Pyspark从与 Pyspark 中的给定查询相同的行返回数据
【发布时间】:2015-01-13 23:39:52
【问题描述】:

在 Pyspark(一种 Spark/Hadoop 输入语言)中:我想在数据集中查找关键字,例如“SJC”,并返回与找到关键字“SJC”的行相对应的第二列中的文本。

例如,以下数据集读取:

[年份] [延误] [目的地] [航班号]

|1987| |-5| |SJC| |500|

|1987| |-5| |SJC| |250|

|1987| |07| |旧金山| |700|

|1987| |09| |SJC| |350|

|1987| |-5| |SJC| |650|

我希望能够查询“SJC”并将 [Delay] 值作为列表或字符串返回。

我已经走到这一步了,但没有运气:

import sys
from pyspark import SparkContext

logFile = "hdfs://<ec2 host address>:9000/<dataset folder (on ec2)>"
sc = SparkContext("local", "simple app")
logData = sc.textFile(logFile).cache()
numSJC = logData.filter(lambda line: 'SJC' in line).first()

print "Lines with SJC:" + ''.join(numSJC)

感谢您的帮助!

【问题讨论】:

    标签: python amazon-ec2 apache-spark pyspark


    【解决方案1】:

    你几乎已经自己完成了

    假设您有一个以竖线分隔的文件 `/tmp/demo.txt':

    Year|Delay|Dest|Flight #
    1987|-5|SJC|500
    1987|-5|SJC|250
    1987|07|SFO|700
    1987|09|SJC|350
    1987|-5|SJC|650
    

    在 PySpark 中你应该这样做:

    # First, point Spark to the file
    log = sc.textFile('file:///tmp/demo.txt')
    # Second, replace each line with array of the values, thus string 
    # '1987|-5|SJC|500' is replaced with ['1987', '-5', 'SJC', '500']
    log = log.map(lambda line: line.split('|'))
    # Now filter leaving only the lists with 3rd element equal to 'SJC'
    log = log.filter(lambda x: x[2]=='SJC')
    # Now leave only the second column, 'Delay'
    log = log.map(lambda x: x[1])
    # And here's the result
    log.collect()
    

    【讨论】:

    • 我还没有尝试过这个算法,但我一定会让你知道它是怎么回事!谢谢-安迪
    • 啊...它工作,谢谢!只是想知道,而不是管道分隔的数据,如果数据只是在 Excel 电子表格的不同行中怎么办?有没有办法做同样的事情?谢谢!
    • Excel 文件无法原生解析,认为唯一的选择是使用 wholeBinaryFiles 加载它们,然后使用一些第 3 方 xls 解析库进行解析。如果不同中的数据可能有问题,你的意思是不同的列吗?
    • 糟糕!是的,列不是行。
    • 对不起,函数名只是binaryFiles
    猜你喜欢
    • 2015-05-28
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2019-02-25
    • 2021-08-18
    相关资源
    最近更新 更多