与SelectExpr条件的pyspark计数

发布于 2025-01-27 06:01:40 字数 496 浏览 2 评论 0原文

我有一个带有“年龄”列的数据框架,例如,我想计算多少行= 60。我知道如何使用select或df.count()解决此问题,但是我想使用selectexpr。

我尝试了

customerDfwithAge.selectExpr("count(when(col(age) = 60))")

,但是

Undefined function: 'col'. This function is neither a registered temporary function nor a permanent function registered in the database 'default'.;

如果我尝试删除 col ,它会返回我,这会使我返回

Invalid arguments for function when; line 1 pos 6

什么问题?

I have a DataFrame with a column "age" and I want to count how many rows with age = 60, for example. I know how to solve this using select or df.count() but I want to use selectExpr.

I tried

customerDfwithAge.selectExpr("count(when(col(age) = 60))")

but it returns me

Undefined function: 'col'. This function is neither a registered temporary function nor a permanent function registered in the database 'default'.;

If I try to remove col, it returns me

Invalid arguments for function when; line 1 pos 6

What is wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尛丟丟 2025-02-03 06:01:40

如果要使用selectexpr,则需要提供有效的SQL表达式。

()()col()pyspark.sql.functions而不是SQL表达式。

在您的情况下,您应该尝试:

customerDfwithAge.selectExpr("sum(case when age = 60 then 1 else 0 end)")

请记住,我正在使用sum不是count计数将计算每个行(0 s和1 s),它将仅返回数据框架的行总数。

If you want to use selectExpr you need to provide a valid SQL expression.

when() and col() are pyspark.sql.functions not SQL expressions.

In your case, you should try:

customerDfwithAge.selectExpr("sum(case when age = 60 then 1 else 0 end)")

Bear in mind that I am using sum not count. count will count every row (0s and 1s) and it would simply return the total number of rows of your dataframe.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文