首页 > 解决方案 > 如何根据月份和年份值过滤数据

问题描述

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

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


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]))

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

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

并且仍然得到同样的错误。

标签: pysparkfiltercallable

解决方案


这是一个最小的工作示例,我认为您可以适应您的需求:

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|
+------------+------------+-----+

推荐阅读