gpt4 book ai didi

python - PySpark 无法访问使用 StringIndexer 添加的列

转载 作者:太空宇宙 更新时间:2023-11-03 21:26:36 26 4
gpt4 key购买 nike

PySpark - v2.4.0

我尝试将 StringCountry 转换为 IntergerCountry_ID,结果看起来不错。但是当我尝试访问 Country_ID 列时,我得到了 AnalysisException

下面是数据框:

+------+-------+
|UserId|Country|
+------+-------+
| 1| Africa|
| 2| Africa|
| 3| UK|
| 4| Japan|
| 5| UK|
| 6| Japan|
| 7| China|
+------+-------+

这是代码:

from pyspark.ml.feature import StringIndexer
indexer = StringIndexer(inputCol='Country', outputCol='Country_ID')
modified_df = indexer.fit(df).transform(df)

修改后的数据框:

modified_df.select('*').show()

+------+-------+----------+
|UserId|Country|Country_ID|
+------+-------+----------+
| 1| Africa| 1.0|
| 2| Africa| 1.0|
| 3| UK| 0.0|
| 4| Japan| 2.0|
| 5| UK| 0.0|
| 6| Japan| 2.0|
| 7| China| 3.0|
+------+-------+----------+

过滤查询:

modified_df.select('UserId').filter(df['Country_ID'] == 2).show()

以下是异常(exception)情况:

AnalysisException:u'无法解析(UserId,Country)中的列名称“Country_ID”;'

我可以将该列视为 DataFrame 的一部分

modified_df.columns

给予,

['UserId', 'Country', 'Country_ID']

如何使 DataFrame 过滤条件适用于 Country_ID

最佳答案

我认为问题在于您尝试使用错误的 Dataframe 引用访问该列。应使用 modified_df 引用 Country_ID 列。

所以改变

modified_df.select('UserId').filter(df['Country_ID'] == 2).show()

modified_df.select('UserId').filter(modified_df['Country_ID'] == 2).show()

它应该可以工作。由于 df 没有任何列 Country_ID

关于python - PySpark 无法访问使用 StringIndexer 添加的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53799435/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com