![](/img/trans.png)
[英]Is there anyway to copy the data from a single column in a Python pandas dataframe into a string or list for further processing?
[英]Export data from Pyspark Dataframe into Dictionary or List for further processing Python
我試圖在Pyspark確實找到連接組件之后從Pyspark Dataframe中檢索值,但我不知道如何從列表中提取數據。
下面是從我正在使用的大型數據集創建的表的簡化版本。 實質上,通過使用圖的頂點和邊的連接數據來創建下表。 如果組件編號相同,則表示節點(ID)位於相同的圖形結構中。
+---+------------+
| id| component|
+---+------------+
| 0|154618822656|
| 1|154618822656|
| 2|154618822656|
| 3|154618822656|
| 4|420906795008|
| 5|420906795008|
+---+------------+
我已經嘗試了很多東西來將數據提取到我最常用的列表和詞典中。 當我在文檔中嘗試各種方法時,我得到如下輸出:
[Row(id='0', component=154618822656), Row(id='1', component=154618822656)]
我不知道該怎么做。 我在Pyspark中也看到了一個asDict()方法,但即使是一個簡單的表,也無法讓它工作。
這是一個示例函數,它接受graphframe,查找連接的組件並創建表。 一切都很好,直到我想將數據放在另一個結構中:
def get_connected_components(graphframe):
connected_table = g.connectedComponents()
connected_table.collect()
conn = connected_table.rdd.take(2)
print(conn)
我最終想要這樣的東西:
{"154618822656" : {0, 1}, "420906795008": {2, 3, 4, 5}}
我會變成另一個輸出,如:
0 1
2 3 4 5
這可能是如何操作這些表格的錯誤路線,但我對Pyspark來說是全新的,並且驚訝於即使在所有搜索中這也是多么棘手。 先感謝您。
不完全確定你要做什么,但這里有一些關於字典和列表轉換的方法,通過Spark應該有所幫助。 需要注意的一件非常重要的事情是,如果你想使用像list / dict這樣的結構,那么我建議你在一台機器上工作(如果你的數據集適合內存),而不是試圖通過Spark分配計算只收集所有數據到一台機器做更多的處理。 由於您正在使用Spark GraphFrames,因此還有一些不錯的單機Python圖形包。 希望這可以幫助。
# load your sample data set
data = [(0, 154618822656),\
(1, 154618822656),\
(2, 154618822656),\
(3, 154618822656),\
(4, 420906795008),\
(5, 420906795008),]
df = spark.createDataFrame(data, ("id", "comp"))
df.show()
+---+------------+
| id| comp|
+---+------------+
| 0|154618822656|
| 1|154618822656|
| 2|154618822656|
| 3|154618822656|
| 4|420906795008|
| 5|420906795008|
+---+------------+
# get desired format like {"154618822656" : {0, 1}, "420906795008": {2, 3, 4, 5}} from your post
from pyspark.sql.functions import collect_list
df.groupBy("comp").agg(collect_list("id").alias("id")).show()
+------------+------------+
| comp| id|
+------------+------------+
|154618822656|[0, 1, 2, 3]|
|420906795008| [4, 5]|
+------------+------------+
# you can convert col to a list ***collect() is not recommended for larger datasets***
l = [i for i in df.select("id").rdd.flatMap(lambda x: x).collect()]
print(type(l))
print(l)
<class 'list'>
[0, 1, 2, 3, 4, 5]
# write to json so you can get a dictionary format like you were mentioning
df.groupBy("comp").agg(collect_list("id").alias("id")).write.json("data.json")
! cat data.json/*.json
{"comp":154618822656,"id":[0,1,2,3]}
{"comp":420906795008,"id":[4,5]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.