美文网首页Python奇技yin巧
pandas中如何提取出某一列(column)的日期数字

pandas中如何提取出某一列(column)的日期数字

作者: 天地本无心 | 来源:发表于2021-04-28 00:41 被阅读0次

这两天,有个小伙伴问我这么一个问题,就是说他公司给了他一个table, 大概是140万行,其中有一列既有数字也有其它字符。例如2021年02月01日,想从里面仅仅把数字提取出来保存成日期格式,比如说2021-02-01,虽然最近忙得飞起,但是看在当年一起读初中的峥嵘岁月,我大概花了5分钟写了一个demo,给他提供了三种解法。

第一步,构造一个fake datasets, 模拟他的需求。

import pandas as pd 
import numpy as np
demo = pd.read_excel("/home/xuzhongtian/Documents/ChenZhenwei_demo.xlsx", header=0)
demo

模拟数据如下:

    City    Date
0   福州  2021年03月01日
1   厦门  2021年03月02日
2   深圳  2021年03月03日
3   武汉  2021年03月04日
4   上海  2021年03月05日
5   青岛  2021年03月06日
6   烟台  2021年03月07日
7   荆州  2021年03月08日

即从Date这一列中,将日期提取出来,保存为2021-03-01这种类型。

解决问题的时候,思维不能太固化。我们既可以通过将数字“提取出来”,也可以选择将除了数字之外的其它字符“抠除”。

略加思忖,给小伙伴提供了三种解法。

方法1:

#方法1:
pattern = "|".join(["年","月","日"])
demo.Date = demo.Date.str.replace(pattern, "-")
demo.Date.str.rstrip("-")

方法1结果:

方法1:Series.str.replace

方法2:

#方法2
demo.Date.str.strip().replace(dict(zip(["年","月","日"],["-","-",""])), regex=True)

方法2结果:

方法2:Series.str.replace

方法3:

temp = demo.Date.str.extract('(\d+).*?(\d+).*?(\d+)') 
temp
temp[0]+"-"+temp[1]+"-"+temp[2]

方法3结果:

方法3:Series.str.extract

方法很多,肯定也不止这几种,但是我们做数据分析,是以解决问题为导向,是在速度和效率之间,寻找一个balance, 毕竟我们知道茴香豆的茴的一种写法,就足够了。


Done!

相关文章

网友评论

    本文标题:pandas中如何提取出某一列(column)的日期数字

    本文链接:https://www.haomeiwen.com/subject/dtymrltx.html