簡體   English   中英

Spark Dataframe 列名更改不反映

[英]Spark Dataframe column name change does not reflect

我正在嘗試重命名我的 spark dataframe 中的一些特殊字符。出於某種奇怪的原因,它在我打印模式時顯示更新的列名,但任何訪問數據的嘗試都會導致錯誤,並抱怨舊的列名。 這是我正在嘗試的:

# Original Schema
upsertDf.columns

# Output: ['col 0', 'col (0)', 'col {0}', 'col =0', 'col, 0', 'col; 0']

for c in upsertDf.columns:
    upsertDf = upsertDf.withColumnRenamed(c, c.replace(" ", "_").replace("(","__").replace(")","__").replace("{","___").replace("}","___").replace(",","____").replace(";","_____").replace("=","_"))
upsertDf.columns

# Works and returns expected result
# Output: ['col_0', 'col___0__', 'col____0___', 'col__0', 'col_____0', 'col______0']

# Print contents of dataframe
# Throws error for original attribute name "
upsertDf.show()

AnalysisException: 'Attribute name "col 0" contains invalid character(s) among " ,;{}()\\n\\t=". Please use alias to rename it.;'

我嘗試了其他選項來重命名該列(使用別名等...),但它們都返回相同的錯誤。 它幾乎就像顯示操作正在使用架構的緩存版本,但我無法弄清楚如何強制它使用新名稱。

有沒有人遇到過這個問題?

看看這個最小的例子(使用你的重命名代碼,在pyspark shell 版本 3.3.1 中運行):

df = spark.createDataFrame(
    [("test", "test", "test", "test", "test", "test")],
    ['col 0', 'col (0)', 'col {0}', 'col =0', 'col, 0', 'col; 0']
)

df.columns
['col 0', 'col (0)', 'col {0}', 'col =0', 'col, 0', 'col; 0']

for c in df.columns:
    df = df.withColumnRenamed(c, c.replace(" ", "_").replace("(","__").replace(")","__").replace("{","___").replace("}","___").replace(",","____").replace(";","_____").replace("=","_"))

df.columns
['col_0', 'col___0__', 'col____0___', 'col__0', 'col_____0', 'col______0']

df.show()
+-----+---------+-----------+------+---------+----------+
|col_0|col___0__|col____0___|col__0|col_____0|col______0|
+-----+---------+-----------+------+---------+----------+
| test|     test|       test|  test|     test|      test|
+-----+---------+-----------+------+---------+----------+

如您所見,這執行成功。 所以你的重命名功能沒問題。

由於您尚未共享所有代碼( upsertDf的定義方式),我們無法真正知道到底發生了什么。 但是查看您的錯誤消息,這來自早於3.2.0的 Spark 版本中的ParquetSchemaConverter.scala (此錯誤消息在3.2.0中更改,請參閱SPARK-34402 )。

確保您讀入數據后立即重命名列,而不進行任何其他操作。

暫無
暫無

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

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