Day 27 [Python ML、资料清理] 处理资料中的时间

设定环境

首先我们需要读取libraries跟dataset,我们将会使用一个dataset是包含在2007~2016间发生地震的情形

# modules we'll use
import pandas as pd
import numpy as np
import seaborn as sns
import datetime

# read in our data
landslides = pd.read_csv("./catalog.csv")

# set seed for reproducibility
np.random.seed(0)

确定时间列的资料型态

landslides.head()

我们将会处理date的column,因此要确报资料中包含日期资料

# print the first few rows of the date column
print(landslides['date'].head())
0     3/2/07
1    3/22/07
2     4/6/07
3    4/14/07
4    4/15/07
Name: date, dtype: object

我们是人类所以看得懂日期资料,但这不代表说python也看得懂这些资料

而且我们注意到这笔资料的type是object

pandas使用object资料型态来代表许多资料型态,但最常会出现的是String

一般若是日期资料,会取得的资料型态应该会是datetime64,我们可以使用dtype来看资料型态是什麽

# check the data type of our date column
landslides['date'].dtype
dtype('O')

资料型态O代表object的意思

转换时间列的资料型态成datatime

我们可以使用以下的方法来format资料,并且让资料型态改为datetime

# Create a new column, date_parsed, with the parsed dates
landslides['date_parsed'] = pd.to_datetime(landslides['date'], format="%m/%d/%y")

然後我们来看一下format完之後的资料

# print the first few rows
landslides['date_parsed'].head()
0   2007-03-02
1   2007-03-22
2   2007-04-06
3   2007-04-14
4   2007-04-15
Name: date_parsed, dtype: datetime64[ns]
# get the day of the month from the date_parsed column
day_of_month_landslides = landslides['date_parsed'].dt.day
day_of_month_landslides.head()
0     2.0
1    22.0
2     6.0
3    14.0
4    15.0
Name: date_parsed, dtype: float64

资料型态一定要是datetime,才能使dt这个方式取得资料

绘制月份的日期以检查日期是否正确

我们将资料转换为直方图来确保资料转换过後的日期只有在1~31之间

# remove na's
day_of_month_landslides = day_of_month_landslides.dropna()

# plot the day of the month
sns.distplot(day_of_month_landslides, kde=False, bins=31)
/opt/conda/lib/python3.6/site-packages/seaborn/distributions.py:2551: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms).
  warnings.warn(msg, FutureWarning)





<AxesSubplot:xlabel='date_parsed'>


<<:  SQL与NoSQL的连结(一)

>>:  26. 从学生社团到技术社群 x Girls in Tech x 曼陀号计画

[Day09 - UI/UX] UI 绘制

在UI出图之前,我们先确认好目前的 wireframe 是完整的。接下来只要依照 wireframe...

Day22【JS】ES6 动态计算属性名 Computed property names

在 ES6 以前,要取得物件只能用 物件.属姓名 或 物件[属姓名] 这样的写法。 其中 [] 内只...

Python入门 Day 6 : # While True的用法

while 是循环结构(while一定要小写),while 後面搭配布林值(boolean)并用,F...

Day7 JS-Callback

在进入下一个NodeJS部份前想先讲一下Callback(回呼),这个概念不会占太大的篇幅,所以这篇...

进击的软件工程师之路-软件战斗营 第六周

学习进度 游戏专题 Delay 地图编辑器使用 (自学)人物移动&转向 (自学)子弹360度...