我無法創建我需要的整個 PySpark Dataframe。我目前的字典是這種格式:
d = {0:
{'Key Features': ['Obese', 'Exercise']},
'Properties': {'Balding': True, 'Tall': False, 'Obese': True, 'Exercise': False}},
1:
{'Key Features': [None]},
'Properties': {'Balding': True, 'Tall': False, 'Obese': False, 'Exercise': True}},
...}
我想以這種格式創建一個資料框:
--------- ------ ------- ---------- ---------------------
|'Balding'|'Tall'|'Obese'|'Exercise'| 'Key Features'|
--------- ------ ------- ---------- ---------------------
| true| false| false| false|['Obese', 'Exercise']|
--------- ------ ------- ---------- ---------------------
| true| false| false| true| [None]|
--------- ------ ------- ---------- ---------------------
我能夠使用以下代碼為“屬性”創建一個資料幀:
df = spark.createDataFrame([d[i]['Properties'] for i in d]).show()
輸出此資料幀:
--------- ------ ------- ----------
|'Balding'|'Tall'|'Obese'|'Exercise'|
--------- ------ ------- ----------
| true| false| false| false|
--------- ------ ------- ----------
| true| false| false| true|
--------- ------ ------- ----------
我曾嘗試添加這樣的列,但失敗了:
df.withColumn('Key Features', array(lit([d[i]['Key Features'] for i in d])
但它只是失敗并且不會將串列添加為列。我試圖創建一個這樣的 DataFrame ,但它也不起作用:
df = spark.createDataFrame([d[i]['Key Features'] for i in d]).show()
輸出:輸入行沒有架構所需的預期值數。提供 1 個值時需要 4 個欄位。
我將如何通過在 createDataFrame 的開頭添加或使用 withColumn 將“關鍵功能”添加為包含在字典中的串列的列?
uj5u.com熱心網友回復:
我認為您的示例輸入d有點格式錯誤,因為它'Properties'與0and處于同一級別1,因此'Properties'在頂層有多個鍵。鑒于您如何索引到d,我將假設d看起來像這樣。如果我的假設有誤,請告訴我,我會盡力糾正答案。
d = {
0: {
'Key Features': ['Obese', 'Exercise'],
'Properties': {'Balding': True, 'Tall': False, 'Obese': True, 'Exercise': False},
},
1: {
'Key Features': [None],
'Properties': {'Balding': True, 'Tall': False, 'Obese': False, 'Exercise': True},
},
}
您可以使用它創建所需的資料框。
df = spark.createDataFrame(
[
{"Key Features": v["Key Features"], **v["Properties"]}
for v in d.values()
]
)
df.show()
------- -------- ----------------- ----- -----
|Balding|Exercise| Key Features|Obese| Tall|
------- -------- ----------------- ----- -----
| true| false|[Obese, Exercise]| true|false|
| true| true| [null]|false|false|
------- -------- ----------------- ----- -----
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/390219.html
上一篇:終于!Spring Boot 最新版發布,一招解決 Log4j2 核彈級漏洞!
下一篇:并發編程
