pyspark學(xué)習(xí)筆記(一)

在ipython notebook下運(yùn)行pyspark

jupyter notebook
from pyspark import SparkConf, SparkContext

appName = 'testSpark'

def main(sc):
    pass

if __name__ == '__main__':
    #Configure Spark
    
    conf = SparkConf().setAppName(appName).setMaster('local[2]')
#     sc.stop()
    sc = SparkContext(conf=conf)
    
    print sc.version
    main(sc)
2.0.2

在瀏覽器輸入ip:4040進(jìn)入到spark的任務(wù)UI界面淹仑,查看各任務(wù)的信息


ip:4040查看任務(wù)UI

pyspark-rdd

參數(shù)preservesPartitioning表示是否保留父RDD的partitioner分區(qū)信息

map

map(f, preservesPartitioning=False)

Return a new RDD by applying a function to each element of this RDD.

#map function
x = sc.parallelize([1,2,3,4])
y = x.map(lambda x:(x, x**3))

print y.collect()
[(1, 1), (2, 8), (3, 27), (4, 64)]

flatMap

flatMap(f, preservesPartitioning=False)

Return a new RDD by first applying a function to all elements of this RDD, and then flattening the results.

z = x.flatMap(lambda x: (x, 100*x, x**2))
print z.collect()
[1, 100, 1, 2, 200, 4, 3, 300, 9, 4, 400, 16]

glom

glom()

Return an RDD created by coalescing all elements within each partition into a list.

rdd = sc.parallelize([1, 2, 3, 4], 2)
print sorted(rdd.glom().collect())
[[1, 2], [3, 4]]

mapPartitions

mapPartitions(f, preservesPartitioning=False)

Return a new RDD by applying a function to each partition of this RDD.

x = sc.parallelize([1,2,3,4], 2)
def f(iter):
    yield sum(iter)
y = x.mapPartitions(f)
# glom() flattens elements on the same partition
print 'x原來分區(qū)信息:{0}'.format(x.glom().collect())
print 'x經(jīng)過f計(jì)算后的結(jié)果:{}'.format(y.glom().collect())
x原來分區(qū)信息:[[1, 2], [3, 4]]
x經(jīng)過f計(jì)算后的結(jié)果:[[3], [7]]

mapPartitionsWithIndex

mapPartitionsWithIndex(f, preservesPartitioning=False)?

Return a new RDD by applying a function to each partition of this RDD, while tracking the index of the original partition.

x = sc.parallelize([1, 2, 3, 4], 2)
def f(splitIndex, iterator): yield (splitIndex, sum(iterator))

y = x.mapPartitionsWithIndex(f)
print 'x原來分區(qū)信息:{0}'.format(x.glom().collect())
print 'x經(jīng)過f計(jì)算后的結(jié)果:{}'.format(y.glom().collect()) 
x原來分區(qū)信息:[[1, 2], [3, 4]]
x經(jīng)過f計(jì)算后的結(jié)果:[[(0, 3)], [(1, 7)]]

getNumsPartitions

getNumPartitions()

Returns the number of partitions in RDD

rdd = sc.parallelize([1, 2, 3, 4], 2)
print '分區(qū)有{}個(gè)'.format(rdd.getNumPartitions())
分區(qū)有2個(gè)

filter

filter(f)

Return a new RDD containing only the elements that satisfy a predicate.

rdd = sc.parallelize([1, 2, 3, 4, 5])
res = rdd.filter(lambda x: x % 2 == 0).collect()
print '符合條件的數(shù)據(jù)是:{}'.format(res)
符合條件的數(shù)據(jù)是:[2, 4]

distinct

distinct(numPartitions=None)

Return a new RDD containing the distinct elements in this RDD.

res = sorted(sc.parallelize([1, 1, 1, 2, 3, 2, 3]).distinct().collect())
print '去重后的結(jié)果:{}'.format(res)
去重后的結(jié)果:[1, 2, 3]

sample

sample(withReplacement, fraction, seed=None)

Return a sampled subset of this RDD.

Parameters:
withReplacement – can elements be sampled multiple times (replaced when sampled out)

fraction – expected size of the sample as a fraction of this RDD’s size without replacement: probability that each element is chosen; fraction must be [0, 1] with replacement: expected number of times each element is chosen; fraction must be >= 0

seed – seed for the random number generator

rdd = sc.parallelize(range(7), 2)
samList = [rdd.sample(False, 0.5) for i in range(5)]
print 'rdd.collect()的值是{}'.format(rdd.collect())

for index, d in zip(range(len(samList)), samList):
    print 'sample: {0} y = {1}'.format(index, d.collect())

takeSample

takeSample(withReplacement, num, seed=None)?

Return a fixed-size sampled subset of this RDD.

Note that this method should only be used if the resulting array is expected to be small, as all the data is loaded into the driver’s memory.

rdd = sc.parallelize(range(15), 2)
samList = [rdd.takeSample(False, 4) for i in range(5)]
print 'rdd.collect()的值是{}'.format(rdd.glom().collect())

for index, d in zip(range(len(samList)), samList):
    print 'sample: {0} y = {1}'.format(index, d)
rdd.collect()的值是[[0, 1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13, 14]]
sample: 0 y = [8, 9, 7, 2]
sample: 1 y = [12, 1, 10, 4]
sample: 2 y = [8, 12, 2, 6]
sample: 3 y = [9, 8, 12, 14]
sample: 4 y = [10, 4, 8, 2]

union

union(other)

Return the union of this RDD and another one.

rdd = sc.parallelize([1, 1, 2, 3])
rdd1 = sc.parallelize([5, 3, 4, 6])
print rdd.union(rdd1).collect()
[1, 1, 2, 3, 5, 3, 4, 6]

intersection

intersection(other)

Return the intersection of this RDD and another one. The output will not contain any duplicate elements, even if the input RDDs did.

Note that this method performs a shuffle internally.

rdd = sc.parallelize([1, 1, 2, 3])
rdd1 = sc.parallelize([5, 3, 4, 6])
print rdd.intersection(rdd1).collect()
[3]

sortByKey

sortByKey(ascending=True, numPartitions=None, keyfunc=func)

Sorts this RDD, which is assumed to consist of (key, value) pairs.

tmp = [('a', 1), ('f', 2), ('d', 3), ('c', 4), ('b', 5)]
rdd = sc.parallelize(tmp, 2)
print rdd.glom().collect()
sort1 = rdd.sortByKey(True,1).glom().collect()
sort2 = rdd.sortByKey(True,3).glom().collect()
print sort1
print sort2
[[('a', 1), ('f', 2)], [('d', 3), ('c', 4), ('b', 5)]]
[[('a', 1), ('b', 5), ('c', 4), ('d', 3), ('f', 2)]]
[[('a', 1), ('b', 5)], [('c', 4), ('d', 3)], [('f', 2)]]
sortByKey
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末枉昏,一起剝皮案震驚了整個(gè)濱河市灾票,隨后出現(xiàn)的幾起案子芥吟,更是在濱河造成了極大的恐慌,老刑警劉巖恶导,帶你破解...
    沈念sama閱讀 222,807評(píng)論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異鬼贱,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)香璃,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,284評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門这难,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人葡秒,你說我怎么就攤上這事姻乓。” “怎么了眯牧?”我有些...
    開封第一講書人閱讀 169,589評(píng)論 0 363
  • 文/不壞的土叔 我叫張陵蹋岩,是天一觀的道長。 經(jīng)常有香客問我学少,道長剪个,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,188評(píng)論 1 300
  • 正文 為了忘掉前任版确,我火速辦了婚禮扣囊,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘绒疗。我一直安慰自己侵歇,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,185評(píng)論 6 398
  • 文/花漫 我一把揭開白布忌堂。 她就那樣靜靜地躺著,像睡著了一般酗洒。 火紅的嫁衣襯著肌膚如雪士修。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,785評(píng)論 1 314
  • 那天樱衷,我揣著相機(jī)與錄音棋嘲,去河邊找鬼。 笑死矩桂,一個(gè)胖子當(dāng)著我的面吹牛沸移,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播侄榴,決...
    沈念sama閱讀 41,220評(píng)論 3 423
  • 文/蒼蘭香墨 我猛地睜開眼雹锣,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了癞蚕?” 一聲冷哼從身側(cè)響起蕊爵,我...
    開封第一講書人閱讀 40,167評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎桦山,沒想到半個(gè)月后攒射,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體醋旦,經(jīng)...
    沈念sama閱讀 46,698評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,767評(píng)論 3 343
  • 正文 我和宋清朗相戀三年会放,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了饲齐。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,912評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡咧最,死狀恐怖捂人,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情窗市,我是刑警寧澤先慷,帶...
    沈念sama閱讀 36,572評(píng)論 5 351
  • 正文 年R本政府宣布,位于F島的核電站咨察,受9級(jí)特大地震影響论熙,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜摄狱,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,254評(píng)論 3 336
  • 文/蒙蒙 一脓诡、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧媒役,春花似錦祝谚、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,746評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至穿仪,卻和暖如春席爽,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背啊片。 一陣腳步聲響...
    開封第一講書人閱讀 33,859評(píng)論 1 274
  • 我被黑心中介騙來泰國打工只锻, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人紫谷。 一個(gè)月前我還...
    沈念sama閱讀 49,359評(píng)論 3 379
  • 正文 我出身青樓齐饮,卻偏偏與公主長得像,于是被迫代替她去往敵國和親笤昨。 傳聞我的和親對(duì)象是個(gè)殘疾皇子祖驱,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,922評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容

  • 嘰嘰喳喳樹上啼, 四處飄零各東西瞒窒。 我笑白云與飛鳥羹膳, 結(jié)伴高飛幾歡喜。
    暖心小屋閱讀 265評(píng)論 7 11
  • 14天寫作訓(xùn)練之第十二天 叮叮當(dāng)根竿,叮叮當(dāng)陵像,鈴兒響叮當(dāng)………平安夜就珠,大家都平安快樂。 2016年馬上就要結(jié)束了醒颖,該給...
    worldlyf閱讀 243評(píng)論 0 0
  • 今天是我第一次寫教學(xué)反思妻怎,雖然早已聞之教學(xué)反思的重要性,可總是因?yàn)閼卸璧男愿襁t遲不愿意動(dòng)手泞歉。 下周就要期中考試...
    徒老小李閱讀 710評(píng)論 0 0
  • 1 有時(shí)候想有個(gè)孩子逼侦,自己的孩子。因?yàn)橛X得這是另一種形式的重生腰耙,自己部分特性轉(zhuǎn)移到一個(gè)新生的肉體榛丢。但這個(gè)想法還沒實(shí)...
    GINGSANG閱讀 194評(píng)論 0 0
  • 拉里金是美國著名主持人,他主持的《拉里金現(xiàn)場(chǎng)秀》播出45年挺庞,創(chuàng)下無數(shù)記錄晰赞,拉里金采訪過的名人數(shù)不勝數(shù),45年來选侨,共...
    談判顧問謝輝閱讀 1,802評(píng)論 0 0