2016-05-18 12 views
6

私は1000のファイルを含むS3のバケットを持っています。それぞれ約1GBです。私はこのファイルのサンプルをランダムに読みたいと思います。すべてのファイルの5%を考えてみましょう。これは私がそれを行う方法PysparkでS3のファイルの無作為なサンプルを読む

fileDF = sqlContext.jsonRDD(self.sc.textFile(self.path).sample(withReplacement=False, fraction=0.05, seed=42).repartition(160))

である。しかし、それは、上記のコードと思われるすべてのファイルを読み込み、その後、試料を採取します。私はファイルのサンプルを取って読んでいますが。誰かが助けてくれましたか?

+0

自己パスとは何ですか?グッビングを使用していますか? – nkadwa

+0

_self.path_はPythonの自己変数です。 – neikusc

答えて

2

、パスのファイルをリスト名のサンプルを採取した後、RDD組合を使用するようにお好みの方法を使用します。

import pyspark 
import random 

sc = pyspark.SparkContext(appName = "Sampler") 
file_list = list_files(path) 
desired_pct = 5 
file_sample = random.sample(file_list, int(len(file_list) * desired_pct/100)) 
file_sample_rdd = sc.emptyRDD() 
for f in file_sample: 
    file_sample_rdd = file_sample_rdd.union(sc.textFile(f)) 
sample_data_rdd = file_sample_rdd.repartition(160) 

ここで一覧表示されます「list_files」の一つの可能​​迅速かつ汚い実装ですS3の "ディレクトリ"下のファイル:

import os 
def list_files(path, profile = None): 
    if not path.endswith("/"): 
     raise Exception("not handled...") 
    command = 'aws s3 ls %s' % path 
    if profile is not None: 
     command = 'aws --profile %s s3 ls %s' % (profile, path) 
    result = os.popen(command) 
    _r = result.read().strip().split('\n') 
    _r = [path + i.strip().split(' ')[-1] for i in _r] 
    return _r 
+0

これは素晴らしいアイデアです。ご回答どうもありがとうございました! – neikusc

関連する問題