处理大量行时的空图

时间:2017-09-27 14:45:45

标签: python python-3.x pandas matplotlib plot

我尝试使用下面的代码绘制图表,以按天显示每小时的速度。

import pandas as pd
import datetime
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
import glob, os

taxi_df = pd.read_csv('ChicagoTaxi.csv')

taxi_df['trip_start_timestamp'] = pd.to_datetime(taxi_df['trip_start_timestamp'], format = '%Y-%m-%d %H:%M:%S', errors = 'raise')
taxi_df['trip_end_timestamp'] = pd.to_datetime(taxi_df['trip_end_timestamp'], format = '%Y-%m-%d %H:%M:%S', errors = 'raise')

#For filtering away any zero values when trip_Seconds or trip_miles = 0
filterZero = taxi_df[(taxi_df.trip_seconds != 0) & (taxi_df.trip_miles != 0)]
filterZero['trip_seconds'] = filterZero['trip_seconds']/60
filterZero['trip_seconds'] = filterZero['trip_seconds'].apply(lambda x: round(x,0))
filterZero['speed'] = filterZero['trip_miles']/filterZero['trip_seconds']
filterZero['speed'] *= 60

filterZero = filterZero.reset_index(drop=True)

filterZero.groupby(filterZero['trip_start_timestamp'].dt.strftime('%w'))['speed'].mean().plot()
plt.xlabel('Day')
plt.ylabel('Speed(Miles per Minutes)')
plt.title('Mean Miles per Hour By Days')
plt.show() #Not working

示例行

0        2016-01-13 06:15:00   8.000000
1        2016-01-22 09:30:00  10.500000

小数据集:[1250219行x 2列]

大数据集:[15172212行x 2列]

对于较小的数据集,代码完美运行并显示图表。然而,当我尝试使用具有1500万行的数据集时,显示的图是空的,因为值是" inf"尽管运行mean()。我在这里做错了吗?

0    inf
1    inf
...
5    inf
6    inf

速度是"每小时英里数"白天!我正在尝试所有时间格式,所以图片中的不匹配对不起。

失败的绘图图像(较大的数据集):

enter image description here

成功绘图的图像(较小的数据集):

enter image description here

1 个答案:

答案 0 :(得分:0)

我无法确定,因为您没有提供数据集的真实示例,但我非常确定您的问题来自专栏trip_seconds

请参阅以下两行:

filterZero['trip_seconds'] = filterZero['trip_seconds']/60
filterZero['trip_seconds'] = filterZero['trip_seconds'].apply(lambda x: round(x,0))

如果trip_seconds列中的某些值≤30,则此行会将它们舍入为0.0。

filterZero['speed'] = filterZero['trip_miles']/filterZero['trip_seconds']

因此,此行将填充一些inf值(任何/ 0.0 = inf)。如果数组mean()的值为inf,则无论如何都会返回inf

需要考虑两件事:

  1. 如果trip_seconds列中的值实际上是以秒为单位,那么在将值除以60之后,它们将以分钟为单位,这将使您的速度以英里/分钟为单位,而不是每小时。

  2. 你应该尝试不用四舍五入的时间