繁体   English   中英

使用正则表达式有效地用pandas中另一列的值替换一列中的部分值?

[英]Efficiently replace part of value from one column with value from another column in pandas using regex?

我有一个pandas dataframe df ,日期为字符串:

Date1        Date2
2017-08-31   1970-01-01 17:35:00
2017-10-31   1970-01-01 15:00:00
2017-11-30   1970-01-01 16:30:00
2017-10-31   1970-01-01 16:00:00
2017-10-31   1970-01-01 16:12:00

我想要做的就是替换每个日期部分的Date2 ,在相应的日期列Date1 ,但留下的时间不变,所以输出:

Date1        Date2
2017-08-31   2017-08-31 17:35:00
2017-10-31   2017-10-31 15:00:00
2017-11-30   2017-11-30 16:30:00
2017-10-31   2017-10-31 16:00:00
2017-10-31   2017-10-31 16:12:00

我已经使用pandas replace和regex这样做了

import re
date_reg = re.compile(r"([0-9]{4}\-[0-9]{2}\-[0-9]{2})")
df['Market Close Time'].replace(to_replace=date_reg, value=df['Date1'], inplace=True)

但对于只有150k行的数据帧,此方法非常慢(> 10分钟)。

这个帖子的解决方案实现了numpy np.where ,速度要快得多 - 如何在这个例子中使用np.where ,还是有另一种更有效的方法来执行这个操作?

一个想法是:

df['Date3'] =  ['{} {}'.format(a, b.split()[1]) for a, b in zip(df['Date1'], df['Date2'])]

要么:

df['Date3'] = df['Date1'] + ' ' + df['Date2'].str.split().str[1]
print (df)
        Date1                Date2                Date3
0  2017-08-31  1970-01-01 17:35:00  2017-08-31 17:35:00
1  2017-10-31  1970-01-01 15:00:00  2017-10-31 15:00:00
2  2017-11-30  1970-01-01 16:30:00  2017-11-30 16:30:00
3  2017-10-31  1970-01-01 16:00:00  2017-10-31 16:00:00
4  2017-10-31  1970-01-01 16:12:00  2017-10-31 16:12:00

要么:

df['Date3'] = pd.to_datetime(df['Date1']) + pd.to_timedelta(df['Date2'].str.split().str[1])
print (df)
        Date1                Date2               Date3
0  2017-08-31  1970-01-01 17:35:00 2017-08-31 17:35:00
1  2017-10-31  1970-01-01 15:00:00 2017-10-31 15:00:00
2  2017-11-30  1970-01-01 16:30:00 2017-11-30 16:30:00
3  2017-10-31  1970-01-01 16:00:00 2017-10-31 16:00:00
4  2017-10-31  1970-01-01 16:12:00 2017-10-31 16:12:00

时间

In [302]: %timeit df['Date3'] =  ['{} {}'.format(a, b.split()[1]) for a, b in zip(df['Date1'], df['Date2'])]
30.2 ms ± 137 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [303]: %timeit df['Date3'] = df['Date1'] + ' ' + df['Date2'].str.split().str[1]
66.4 ms ± 3.18 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

另一种方式是

df.Date2 = df.Date1.str[:].values + df.Date2.str[10:].values

df.Date1.str[:].valuesDate1字段作为numpy数组,同样使用Date2字段。

str[10:]用于提取Date2的时间部分,该部分附加到Date1的日期。

计时: 2.26 ms±82.2μs

%timeit df.d2 = df.d1.str[:].values + df.d2.str[10:].values
2.26 ms ± 82.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM