python - 使用正则表达式替换 Pandas 数据框中字符串的特定部分

标签 python regex pandas numpy substring

我的数据框有一个日期列(当前是字符串)。我正在尝试解决该色谱柱的问题。

df[:15]

    Date    Customer ID
0   01/25/2016  104064596300
1   02/28/2015  102077474472
2   11/17/2016  106430081724
3   02/24/2016  107770391692
4   10/05/2016  106523680888
5   02/24/2016  107057691592
6   11/24/2015  102472820188
7   10/12/2016  107195498128
8   01/05/2016  104796266660
9   09/30/2016  107812562924
10  10/13/2015  102809057000
11  11/21/2016  107379017712
12  11/08/2015  106642145040
13  02/26/2015  107862343816
14  10/16/2016  107383084928

我的数据应该在以下日期范围内:2015 年 9 月至 2016 年 2 月。

一些数据的年份混淆了(例如,参见上面第 2 行 - 2016 年 11 月 17 日!)

我想做的是更改日期不正确的观测年份。

我已经在 Pandas 中使用了 Replace() 命令,但无法找到有效的命令:

df.Date.str.replace(('^(09|10|11|12)\/\d\d\/2016$'), '2015')

0         01/25/2016
1         02/28/2015
2               2015
3         02/24/2016
4               2015
5         02/24/2016
6         11/24/2015
7               2015
8         01/05/2016
9               2015
10        10/13/2015
11              2015
12        11/08/2015
13        02/26/2015
14              2015
15        12/17/2015
16        01/05/2015
17        01/21/2015
18              2015
19              2015
20        02/06/2016
21        10/06/2015
22        02/18/2016

具体来说,我只是想根据某些条件更改每行的最后 4 位数字(年份):

  1. 如果月份在 9 月到 12 月(09 到 12)之间并且有年份 2016 年,将此观测的年份更改为 2015 年

  2. 如果月份是 1 月或 2 月(01 或 02)且年份为 2015 年,则将此观测的年份更改为 2016

我上面写的命令识别了场景 1) 的正确观察结果,但我在替换最后 4 位数字并将结果输入回原始数据框中时遇到了问题。

最后一点:您可能会想,为什么我不简单地将列更改为日期时间类型,然后根据我的需要添加或减去年份呢?如果我尝试这样做,我将遇到错误,因为某些观察的日期为:2/29/2015 -> 您将遇到错误,因为 2015 年期间没有 2 月 29 日!

最佳答案

不要将日期视为字符串。可以先将日期的字符串格式转换为时间戳,然后进行切片。

import pandas ad pd
df.loc[:, 'Date'] = pd.DatetimeIndex(df['Date'], name='Date')
df = df.set_index('Date')
df['2015-09': '2016-02']

更新:

df.loc[:, 'year_month'] = df.Date.map(lambda s: int(s[-4:]+s[:3]))
df.query('201509<=year_month<=201602').drop('year_month', axis=1)

抱歉,我误解了你的问题。

def transform(date_string):
    year = date_string[-4:]
    month = date_string[:2]
    day = date_string[3:5]
    if year== '2016' and month in ['09', '10', '11', '12']:
        return month + '/' + day + '/' + str(int(year)-1)
    elif year == '2015' and month in ['01', '02', '03']:
        return month + '/' + day + '/' + str(int(year)+1)
    else:
        return date_string

df.loc[:, 'Date'] = df.Date.map(transform)

关于python - 使用正则表达式替换 Pandas 数据框中字符串的特定部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39402154/

相关文章:

python - Python 2/3 中的编码/解码有什么区别

mysql - 清理充满 html 标签的旧数据库

javascript - 使用 RegExp 查找、复制和粘贴标签内容

java - 为什么关闭方括号 "]"不需要在正则表达式中转义?

python - 在 python pandas 的数据框中使用选定的列为每一行数据创建哈希值

python - 如何为同一个 pandas Dataframe 中的 18 个不同列制作 18 个独立的散点图?

python - Selenium3.4.0-Python3.6.1 : In Selenium-Python binding using unittest how do I decide when to use self. assertIn or assert

python - Python 列表是可变的吗?

python - Pandas:删除有限的重复项

python - Pandas 用 nan 值切割了一系列