[英]Remove all StructType columns from PySpark DataFrame
我有一個數據框df
讀取JSON文件,如下所示:
df = spark.read.json("/myfiles/file1.json")
df.dtypes
顯示以下列和數據類型:
id – string Name - struct address - struct Phone - struct start_date - string years_with_company - int highest_education - string department - string reporting_hierarchy - struct
我想只提取非結構列並創建數據框。 例如,我的結果數據框應該只有id
, start_date
, highest_education
和department
。
這是我部分工作的代碼,因為我只獲得填充其中的最后一個非結構列department
的值。 我想收集所有非結構類型列,然后轉換為數據框:
names = df.schema.names
for col_name in names:
if isinstance(df.schema[col_name].dataType, StructType):
print("Skipping struct column %s "%(col_name))
else:
df1 = df.select(col_name).collect()
我很確定這可能不是最好的方法,而且我錯過了一些我無法指責的東西,所以我很感激你的幫助。 謝謝。
使用列表理解:
cols_filtered = [
c for c in df.schema.names
if not isinstance(df.schema[c].dataType, StructType)
]
要么,
# Thank you @pault for the suggestion!
cols_filtered = [c for c, t in df.dtypes if t != 'struct']
現在,您可以將結果傳遞給df.select
。
df2 = df.select(*cols_filtered)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.