簡體   English   中英

從列表中創建pyspark數據幀列,列表的長度與數據幀的行數相同

[英]Making a pyspark dataframe column from a list where the length of the list is same as the row count of the dataframe

我有一個現有的pyspark數據框,其中有170列和841行。 我正在尋找添加另一列,這是“字符串”的列表。 列表的長度為841,名稱為總數

  >>> 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具有1列和841行。 而且,由於沒有公共列可以連接,因此無法將其連接到原始數據框。

我能想到的另一半方法是使用文字。

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>>

並且所有值都只在第一行中,這是不希望的。

當列表的長度與數據框中的行數相同時,是否可以從列表中添加新列?

仍然是使用pyspark的新手

希望這可以幫助!

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()


不要忘記讓我們知道它是否解決了您的問題:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM