首页 > 解决方案 > Pandas 在数据框中搜索日期格式和非日期格式

问题描述

这是我的场景:

我需要搜索。. . 假设以下 3 个术语:“apple”、“candy”和“time”。

我还需要搜索“MM/dd/yyyy”中的任何值。

我需要在整个数据框列“A”列中搜索所有这 4 个内容。

假设我有一个如下所示的数据框:

df4

            A           Q           R           S
0       Apple       chair         red     english
1      orange        desk        blue      german
2        pear     monitor      yellow     spanish
3       Apple       chair      purple     english
4  10/01/2016  05/02/2004  05/05/2014  06/20/2018
5  02/20/2017  01/01/2017  07/07/2017  02/04/2004

我期待的输出是这样的:

            A           Q           R           S
0       Apple       chair         red     english
3       Apple       chair      purple     english
4  10/01/2016  05/02/2004  05/05/2014  06/20/2018
5  02/20/2017  01/01/2017  07/07/2017  02/04/2004

搜索实际单词没有问题。我不知道如何同时搜索单词和搜索日期格式。

有没有人有什么建议?

标签: pythonpython-3.xpandas

解决方案


IIUC,使用str.containsstr.match

vals = ['apple', 'candy', 'time']
df.loc[df.A.str.contains('|'.join(vals), case=False) | df.A.str.match(r'(\d+/\d+/\d+)')]

    A           Q           R           S
0   Apple       chair       red         english
3   Apple       chair       purple      english
4   10/01/2016  05/02/2004  05/05/2014  06/20/2018
5   02/20/2017  01/01/2017  07/07/2017  02/04/2004

推荐阅读