看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
本例我们让试着用 pandas 来找出 2000年1月1日 到 2100年12月31日 之间的回文日。何为回文日呢?就像回文数一样,反正读都一样,比如 20200202 这样的日期。
由于要找的时间范围在 100 年,总体日期数对于计算来说并不大,我们就直接构造一个日期序列为 DataFrame 的第一列,然后再指定一个它的反转日期,然后再筛选每行这两列日期相等的数据,就是我们要的结果。
先构造一个日期序列:
import pandas as pd
df = pd.DataFrame({'date': pd.date_range('20000101', '21001231')})
df
'''
            date
0     2000-01-01
1     2000-01-02
2     2000-01-03
3     2000-01-04
4     2000-01-05
...          ...
36885 2100-12-27
36886 2100-12-28
36887 2100-12-29
36888 2100-12-30
36889 2100-12-31
[36890 rows x 1 columns]
'''
将 date 列,转为 20200202 这样的文本格式:
df.assign(date=df.date.astype(str).str.replace('-', ''))
'''
           date
0      20000101
1      20000102
2      20000103
3      20000104
4      20000105
...         ...
36885  21001227
36886  21001228
36887  21001229
36888  21001230
36889  21001231
[36890 rows x 1 columns]
'''
我们没有使用时间日期的格式化方法,而是直接用了类型转换,再替换掉连字符。
接下来,增加一个反转列。我们使用字符串的切片操作,将步长指定为 -1 便可实现字符反转:
(
    df.assign(date=df.date.astype(str).str.replace('-', ''))
    .assign(other=lambda x: x.date.str[::-1])
)
'''
           date     other
0      20000101  10100002
1      20000102  20100002
2      20000103  30100002
3      20000104  40100002
4      20000105  50100002
...         ...       ...
36885  21001227  72210012
36886  21001228  82210012
36887  21001229  92210012
36888  21001230  03210012
36889  21001231  13210012
[36890 rows x 2 columns]
'''
最后筛选出两列相等的数据:
(
    df.assign(date=df.date.astype(str).str.replace('-', ''))
    .assign(other=lambda x: x.date.str[::-1])
    .query('date == other')
)
'''
           date     other
640    20011002  20011002
3654   20100102  20100102
4323   20111102  20111102
7337   20200202  20200202
8006   20211202  20211202
11018  20300302  20300302
14702  20400402  20400402
18384  20500502  20500502
22068  20600602  20600602
25750  20700702  20700702
29434  20800802  20800802
33117  20900902  20900902
'''
以上日期就是我们最终结果到回文日期。
这样就完成了需求。
(完)
更新时间:2024-08-18 15:59:54 标签:pandas python 日期 回文数