如何解决如果df.ColumnName列名来自Pyspark中的用户如何获取列值
我的代码在Pyspark中的下面:
from FILE_TO_IMPORT import XYZ
我希望ColumnName来自以下用户:
Product = results.where(results.ColumnName == ProductName )
Product.show()
但出现以下错误:
ColumnName = input("enter column name")
基本上,我想检查“产品”列中是否具有该值。 例如
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-64-3e0600c86491> in <module>()
----> 1 Prediction_Product_Wise = results.where(results.ColumnName == ProductName ).select(
ColumnName,'probability','prediction').orderBy("probability",ascending=False)
2 Prediction_Product_Wise.show()
/usr/local/lib/python3.6/dist-packages/pyspark/sql/dataframe.py in __getattr__(self,name)
1399 if name not in self.columns:
1400 raise AttributeError(
-> 1401 "'%s' object has no attribute '%s'" % (self.__class__.__name__,name))
1402 jc = self._jdf.apply(name)
1403 return Column(jc)
AttributeError: 'DataFrame' object has no attribute 'ColumnName'
且数据帧为df,则Product
apple
ball
cat
应返回df.Product == apple
值。
我想让用户在“产品”列的位置,他/她可以根据偏好选择任何列名称。
解决方法
假设ColumnName
是一个字符串,则可以执行此操作。
from pyspark.sql.functions import col
Product = results.where(col(ColumnName) === ProductName)
Product.show()
,
您可以尝试创建类似这样的函数来执行任务。对于数据框中不存在的列,这将返回False。
def is_value(df,column_name: str,value):
if column_name in df.columns:
return bool(df.where(df[column_name] == value).first())
return False
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。