【问题标题】:How to filter data based on the month and year value如何根据月份和年份值过滤数据
【发布时间】:2021-11-25 13:54:28
【问题描述】:

我正在尝试根据日期列中的月份和年份值过滤数据。

我将日期列从字符串转换为日期


df.withColumn('ifrs_year_dt', to_date(unix_timestamp('ifrs_year_dr', 'Mm/dd/yyyy).cast('timestamp)))

df=df.withColumn('month',month(df['ifrs_year_dt]))

我收到错误 int object is not callable,当使用 month() 函数时。我在过滤器里面试​​过了,它的说法是一样的。

df=df.filter(month(df['ifrs_year_dt])==3)

仍然出现同样的错误。

【问题讨论】:

  • month 是什么?

标签: pyspark filter callable


【解决方案1】:

这是一个最小的工作示例,我认为您可以根据自己的需要进行调整:

import pyspark.sql.functions as F
sample_dates = ['09/01/2021',
                '10/01/2021',
                '03/01/2021',
                '07/10/2010']
df = spark.createDataFrame([(date,) for date in sample_dates], ["ifrs_year_dr"])

df_with_date = df.withColumn('ifrs_year_dt', F.to_date(F.unix_timestamp('ifrs_year_dr', 'MM/dd/yyyy').cast('timestamp')))
df_with_month=df_with_date.withColumn('month',F.month(df_with_date['ifrs_year_dt']))
df_with_month.show()
df_with_month.filter(F.col("month") == 3).show()

输出:

+------------+------------+-----+
|ifrs_year_dr|ifrs_year_dt|month|
+------------+------------+-----+
|  09/01/2021|  2021-09-01|    9|
|  10/01/2021|  2021-10-01|   10|
|  03/01/2021|  2021-03-01|    3|
|  07/10/2010|  2010-07-10|    7|
+------------+------------+-----+

+------------+------------+-----+
|ifrs_year_dr|ifrs_year_dt|month|
+------------+------------+-----+
|  03/01/2021|  2021-03-01|    3|
+------------+------------+-----+

【讨论】:

    猜你喜欢
    • 2018-11-23
    • 2019-08-11
    • 1970-01-01
    • 2015-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 2019-12-06
    相关资源
    最近更新 更多