數據分析---pandas--數據清洗

數據清洗:在咱們拿到數據以後,每每會由於各類緣由形成數據異常,可是這時咱們又須要準確的數據進行數據分析,那麼就得先進行數據清洗,以後再進行數據分析。python

1.空值異常數據:

在這裏插入圖片描述

2.點菜時間在作菜時間後異常數據

在這裏插入圖片描述

3.點菜時間和作菜時間在同一時間異常數據

在這裏插入圖片描述

4.時間太長超乎你想像異常數據

在這裏插入圖片描述

import pandas as pd
import numpy as np

order = pd.read_csv('meal_order_info.csv',sep=',',encoding='gbk',engine='python',)
print('原始數據:\n',order.shape)
'''
原始數據:
 (945, 21)
'''

#因爲表中的日期數據爲字符中類型,因此在進行日期操做以前,須要所它們轉換成TimeStape
order['use_start_time'] = pd.to_datetime(order['use_start_time'])
order['lock_time'] = pd.to_datetime(order['lock_time'])

#時間差
order['time']= order['lock_time'] - order['use_start_time']

#異常值的處理
#1.判斷這一列是否有空值,若是有刪除該行數據
index_null = order.index[order['time'].isnull()]

#刪除
order.drop(labels=index_null,axis=0,inplace=True)
print('剔除空值後表的數據:\n',order.shape)
'''
剔除空值後表的數據:
 (936, 22)
'''



#2.關於錯誤值(負值)的清洗,lock_time<start_time
mask = order['lock_time']<order['use_start_time']
# print(mask)
index_fu = order.index[mask]
order.drop(labels=index_fu,axis=0,inplace=True)
print('剔除time爲負值後表的數據:\n',order.shape)
'''
剔除time爲負值後表的數據:
 (913, 22)
'''

# 3.清洗相同時間異常數據
time_exception = (order['time'].astype('str')) == '0 days 00:00:00.000000000'
#注意index裏面填的是具體值而這個方法是爲了得出值爲true的index而後方便咱們下面的drop函數使用刪除具體的哪一行
index_exception = order.index[time_exception]
# print('index_exception',index_exception)
order.drop(labels=index_exception,axis=0,inplace=True)
print('清洗完相同時間的數據:\n',order.shape)
'''
清洗完相同時間的數據:
 (911, 22)
'''


#4.關於異常值的清洗,點餐時間大於1天爲異常數據
# print(order['time'].max())
#查看time,而後根據展現的數據去判斷(82    16 days 00:08:00)若是大於0天的就是異常數據,
#由於考慮到有的人等朋友來了再點餐,全部把時間上限設爲1天
# print(order['time'].head(100),type(order['time']))
#
#str

# 序列.str,表示將序列中的元素(按行),以字符串的形式展現
# order['time'].astype('str')#0 days 00:12:00.000000000
# order['time'].astype('str').str #‘0 days 00:12:00.000000000’

# order['time'].astype('str').str[0]#字符串第一位的值

#生成過濾序列【False,True.....】,把True過濾掉
#得出mask爲true的
mask = (order['time'].astype('str').str[0]).astype('int')>0
#注意index裏面填的是具體值而這個方法是爲了得出值爲true的index而後方便咱們下面的drop函數使用刪除具體的哪一行
index_exception = order.index[mask]
# print('index_exception',index_exception)
order.drop(labels=index_exception,axis=0,inplace=True)

print('全部異常值清洗後的表的數據爲:\n',order.shape)
'''
全部異常值清洗後的表的數據爲:
 (905, 22)
'''
# #
# # 數據分析
print(order['time'].min()) #分析點餐用時最少的時間
print(order['time'].max()) #分析點餐用時最多的時間
print(order['time'].mean()) #分析平均點餐用時的時間

#保存
# fp = pd.ExcelWriter('over.xlsx')
# order.to_excel(fp)
# fp.save()

在這裏插入圖片描述