Fork me on GitHub

pandas时间处理

pandas处理技巧-时间处理

记录pandas中关于时间的两个处理技巧

  • 字符串类型和datatimens类型的转化
  • 如何将时分秒类型的数据转成秒为单位的数据

字符串和时间格式转化

报错

1
2
3
import pandas as pd
from datetime import datetime
import time

当我们导入包含日期数据的时候,有时候需要进行前期的处理,比如:读进来一份包含年月字段的数据

1
df.dtypes  # datetime64[ns]类型数据

当查看数据字段信息的时候发现,发现它是datetime64[ns]类型。

目的是想获取年月信息,去掉最后的01,只取前面的年月,当直接使用split方法的时候,报错如下:

解决

1、先转成字符串类型

1
df["年月"] = df["年月"].apply(lambda x: x.strftime('%Y-%m-%d'))

2、对字符串数据使用split方法

1
df["年月"] = df["年月"].apply(lambda x: x.split("-")[0] + "-" + x.split("-")[1].split("-")[0])

3、如何将字符串又转成datetime64[ns]的数据类型??

1
df["年月"] = pd.to_datetime(df["年月"], format = "%Y-%m-%d")

时分秒的处理

目的

1、记录📝一次时分秒时间的处理。有平均时长这样一个字段:时:分:秒

2、想将上述时长全部转成秒:小时*24+分钟*60+秒

处理步骤

1、转成字符串并单独取出时分秒

1
2
3
4
5
6
7
# 1、先转成字符串
df["平均访问时长"] = df["平均访问时长"].apply(lambda x: x.strftime('%H-%M-%S')) # 先转成字符串

# 2、切割出时分秒
df["小时"] = df["平均访问时长"].apply(lambda x: x.split("-")[0])
df["分钟"] = df["平均访问时长"].apply(lambda x: x.split("-")[1].split("-")[0]) # df["平均访问时长"].apply(lambda x: x.split("-")[-2]) 倒数第二位
df["秒"] = df["平均访问时长"].apply(lambda x: x.split("-")[-1]) # 取出倒数第一位数据

2、检查时、分、秒的统计情况

  • 没有超过1个小时的数据
  • 有00分和超过10分的数据,需要特殊处理;秒也是类似情况

3、分钟的特殊处理

pandas中判断某个字符串的开始和结尾字符:startswith()、endswith();使用了if循环来进行判断:

  • 如果是0开头,但不是0结尾:取出后面的数值
  • 如果是不是0开头,就是数据本身
  • 除了上面两种,剩下的就是00,直接赋值为0
1
2
3
4
5
6
7
for i in range(len(df)):
if df.loc[i,"分钟"].startswith("0") == True and df.loc[i,"分钟"].endswith("0") == False: # 08
df.loc[i,"分钟"] = df.loc[i,"分钟"].split("0")[1]
elif df.loc[i,"分钟"].startswith("0") == False: # 30
df.loc[i,"分钟"] = df.loc[i,"分钟"]
elif df.loc[i,"分钟"] == "00": # 00则赋值为0
df.loc[i,"分钟"] = "0"

4、处理过后的数据(分钟)

5、计算总共的时长(秒为单位)

需要将每个字符串的数据转成int类型,再进行处理

1
2
3
4
5
# 时长:分钟*60 + 秒

for i in range(len(df)):
df.loc[i,"时长"] = int(df.loc[i,"分钟"]) * 60 + int(df.loc[i,"秒"])
df

本文标题:pandas时间处理

发布时间:2021年02月03日 - 14:02

原始链接:http://www.renpeter.cn/2021/02/03/pandas%E6%97%B6%E9%97%B4%E5%A4%84%E7%90%86.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Coffee or Tea