LoginSignup
2

More than 5 years have passed since last update.

Pysparkでテキスト読み込み

Posted at

Pysparkを使ってcsvファイルの読み込みを行います。

  • CSVの行数をカウントする
from pyspark import SparkContext
sc = SparkContext("local")
data = sc.textFile('sample_dataset.csv')
print(data.count())
sc.stop()
  • ファイル内の指定した文字の件数をカウントする
from pyspark import SparkContext

file = "C:\spark-2.3.1-bin-hadoop2.7\README.md" 
# SparkContext("local", "title")の()内は省略できるが、"local"を省略すると遅くなるらしい
sc = SparkContext("local", "sample")
data = sc.textFile(file).cache()

numAs = data.filter(lambda s: 'a' in s).count()
numBs = data.filter(lambda s: 'b' in s).count()

print("a: %i, b: %i" % (numAs, numBs))
sc.stop()

pythonはまだ慣れませんが、
テキストファイルの中身を簡単に取得できます。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2