簡體   English   中英

刪除在Spark數據框中具有句點的列名稱

[英]Dropping a column name that has a period in Spark dataframe

我無法在具有句點的Spark數據框中刪除列。 我知道您需要使用反引號(`)對列名進行轉義。 當我嘗試選擇列時,這確實起作用,並且確實我編寫了自己的小靜態函數來轉義所有列名:

@staticmethod
def escape(columns):
    return ["`" + col + "`" if "." in col else col for col in columns]

然后可以使用它來獲取所需的列列表以供選擇:

desired_columns = MySparkClass.escape(
    list(filter(lambda col: re.search('targetRegexStuffHere', col), target_df.columns))
)

filtered_df = df.select(desired_columns)

使用一個簡單的,可復制的示例:

same = sqlContext.createDataFrame(
    [
        (1, 1, 'A', '2017-01-01'),
        (2, 3, 'B', '2017-01-02'),
        (3, 5, 'A', '2017-01-03'),
        (4, 7, 'B', '2017-01-04')
    ],
    ('index', 'X', 'label.X.L.', 'date')
)

print(same.select('`label.X.L.`').collect())

輸出為:

[Row(label.X.L.='A'), Row(label.X.L.='B'), Row(label.X.L.='A'), Row(label.X.L.='B')]

但是,刪除反引號將導致AnalysisException

pyspark.sql.utils.AnalysisException: 'syntax error in attribute name: label.X.L.;'

但是,當我嘗試放置label.XL列時,反引號似乎沒有任何區別:

print(same.drop('`label.X.L.`').collect())

輸出是

[Row(index=1, X=1, label.X.L.='A', date='2017-01-01'),
 Row(index=2, X=3, label.X.L.='B', date='2017-01-02'),
 Row(index=3, X=5, label.X.L.='A', date='2017-01-03'),
 Row(index=4, X=7, label.X.L.='B', date='2017-01-04')]

刪除名稱中包含句點的列的正確方法是什么?

指定用於select()drop()列的語法略有不同。 當您的select()列名稱中有句點時:

same.select('`label.X.L.`') # note the backticks

但是,當您嘗試放下時:

same.drop('label.X.L.') # note the absence of the backticks

暫無
暫無

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

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