pyspark - 如何根据月份和年份值过滤数据
问题描述
我正在尝试根据日期列中的月份和年份值过滤数据。
我将日期列从字符串转换为日期为
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)
并且仍然得到同样的错误。
解决方案
这是一个最小的工作示例,我认为您可以适应您的需求:
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|
+------------+------------+-----+
推荐阅读
- android - 如何通过appium在移动应用中点击图片
- firebase - Firebase Analytics,规定的事件参数是否也算作自定义参数?
- oracle - 如何在 where 条件下使用 app_user
- python - 如何将 API 响应转换为 JSON 对象?
- azure - Azure 策略将额外资源报告为不合规
- python-3.x - 根据不同条件替换值
- swift - 同色swift的table view和tableview cell
- mysql - 这个 SQL 是如何实现 'row_number' 功能的?
- java - 在自定义原生模块中访问 AppCompatActivity
- javascript - 传递对象时防止在 PureComponent 上重新渲染