2017-07-20 12 views
0

170列と841行を持つ既存のpysparkデータフレームがあります。私はそれに '文字列'のリストである別の列を追加しようとしています。リストの長さは841で、名前はいくつかの方法リストの長さがデータフレームの行数と同じリストからpysparkデータフレーム列を作成する

>>> totals 
['165024392279', '672183', '1002643', '202292', '216254163906', '4698279464', '9247442818', '60093051178', '22208366804', '994475', '12174', '9404969384', '32118344368', '857443', '48544', '24572495416', '43802661492', '35686122552', '780813', '35414800642', '661474', '531615', '31962803064', '111295163538', '531671', '25776968294', '78538019255', '152455113964', '39305504103', '325507', '1028244', '82294034461', '715748', '12705147430', '678604', '90303771130', '1372443', '362131', '59079186929', '436218', '79528', '41366', '89254591311'...] 

一つは、新しいデータフレームを作成し、メインデータフレームでそれに参加することができの合計です。

new_df = sqlContext.createDataFrame([Row(**{'3G-fixated voice users':t})for t in totals]) 

のでnew_dfは841行の1列があります。また、結合する共通の列がないため、元のデータフレームに結合することはできません。

私が考えることができる別の半焼き付けアプローチは、リテラルを使用しています。

from pyspark.sql.functions import array,lit 
totals=[str(t) for t in totals] 
test_lit = array([array([lit(t) for t in tt]) for tt in totals]) 
big_df.withColumn('3G-fixated voice users',test_lit) 

これはタイプ

array<array<string>> 

であり、全ての値のみ望まれていない第1行目に記載されています。新しい列を追加します

リストの長さがデータフレームの行数と同じ場合、リストから新しい列を追加する方法はありますか?

まだ新しいpysparkを使用しています。

答えて

1

希望します。

from pyspark.sql.functions import monotonically_increasing_id 
df = sc.parallelize([(1,2,3,4,5),(6,7,8,9,10),(16,17,18,19,20)]).toDF(['col1','col2','col3','col4','col5']) 
df = df.withColumn("row_id", monotonically_increasing_id()) 

totals_df = sc.parallelize(['xxx','yyy','zzz']).map(lambda x: (x,)).toDF(['totals']) 
totals_df = totals_df.withColumn("row_id", monotonically_increasing_id()) 

final_df = df.join(totals_df, df.row_id == totals_df.row_id) 
final_df = final_df.select([c for c in final_df.columns if c not in {'row_id'}]) 
final_df.show() 


それはあなたの問題を解決した場合はお知らせすることを忘れないでください:)

関連する問題