python - 根据特定日期条件在Python中选择日期列

标签 python pandas jupyter-lab

这是我的示例代码。我的数据库包含一年中每个日期的列,可以追溯到多年前。每列对应一个特定日期。

import pandas as pd
df = pd.DataFrame([[10, 5, 25, 67,25,56], 
                   [20, 10, 26, 45, 56, 34], 
                   [30, 3, 27, 34, 78, 34], 
                   [40, 9, 28, 45, 34,76]], 
                  columns=[pd.to_datetime('2022-09-14'), pd.to_datetime('2022-08-14'), pd.to_datetime('2022-07-14'), pd.to_datetime('2021-09-14'),
                              pd.to_datetime('2020-09-14'), pd.to_datetime('2019-09-14')])

有没有办法根据年、月或季度仅选择符合特定条件的列。

例如,我希望每年只获取与今天(任何开始日期)相同的日期的列。例如,今天是 2022 年 9 月 14 日,我只需要 2021 年 9 月 14 日、2020 年 9 月 14 日等的列。另一种选择可能是按月或按季度执行相同的操作。 在 pandas 中如何做到这一点?

最佳答案

是的,你可以这样做:

# day
df.loc[:, df.columns.day == 14]

   2022-09-14  2022-08-14  2022-07-14  2021-09-14  2020-09-14  2019-09-14
0          10           5          25          67          25          56
1          20          10          26          45          56          34
2          30           3          27          34          78          34
3          40           9          28          45          34          76


# month
df.loc[:, df.columns.month == 9]

   2022-09-14  2021-09-14  2020-09-14  2019-09-14
0          10          67          25          56
1          20          45          56          34
2          30          34          78          34
3          40          45          34          76


# quarter
df.loc[:, df.columns.quarter == 3]

   2022-09-14  2022-08-14  2022-07-14  2021-09-14  2020-09-14  2019-09-14
0          10           5          25          67          25          56
1          20          10          26          45          56          34
2          30           3          27          34          78          34
3          40           9          28          45          34          76

关于python - 根据特定日期条件在Python中选择日期列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73723291/

相关文章:

python - 运行 scipy.spatial.distance.pdist 后提取距离

python - 将数据帧写入 tex 文件时删除索引

python - 如何删除列或数据框中的括号

node.js - 没有 nodejs 无法确定 jupyterlab 构建状态

python - 针对多种类型的 NDB 查询

python - 如何避免全局变量

python - 如何从链接获取文件大小而不用在 python 中下载它?

typescript - 在 TS 文件中的 Vue 组件上使用 VS 调试器时出现 "Unverified Breakpoints"

python-3.x - 如何更改 Jupyter 实验室工作目录

python - 如何在Python中用真实数据测试机器学习模型