使用panda实现以上程序:
import json
from pandas import DataFrame, Series
import pandas as pd
import numpy as np
path = './Python Data Analysis Example_1.txt'
records = [json.loads(line) for line in open(path)]
#print(records[0]['tz'])
time_zones = [rec['tz'] for rec in records if 'tz' in rec]
#print(time_zones[:10])
frame = DataFrame(records)
print(frame['tz'][:10])
输出结果:
0 America/New_York
1 America/Denver
2 America/New_York
3 America/Sao_Paulo
4 America/New_York
5 America/New_York
6 Europe/Warsaw
7
8
9
Name: tz, dtype: object
这里的frame的输出形式是摘要视图,主要用于较大的DataFrame对象。frame[’tz’]所返回的Series对象有一个value_counts方法,该方法可以让我们得到所需要的信息。
tz_counts = frame['tz'].value_counts()
print(tz_counts[ :10])
输出结果:
America/New_York 1251
521
America/Chicago 400
America/Los_Angeles 382
America/Denver 191
Europe/London 74
Asia/Tokyo 37
Pacific/Honolulu 36
Europe/Madrid 35
America/Sao_Paulo 33
Name: tz, dtype: int64
然后我们想利用绘制图库(matplotlib)为这段数据生成一张图片。为此我们先给记录中缺失的时区天上一个替代值,fillna函数可以替换缺失值(NA),而未知值(空字符串)则可以通过布尔数组索引加以替换。
clean_tz = frame['tz'].fillna('Missing')
clean_tz[clean_tz == ''] = 'Unknow'
tz_counts = clean_tz.value_counts()
print(tz_counts[ :10])
输出结果:
America/New_York 1251
Unknow 521
America/Chicago 400
America/Los_Angeles 382
America/Denver 191
Missing 120
Europe/London 74
Asia/Tokyo 37
Pacific/Honolulu 36
Europe/Madrid 35
Name: tz, dtype: int64
利用counts对象的plot方法既可以得到一张水平条形图:
tz_counts[ :10].plot(kind='barh', rot=0)
输出结果:


-
- 0000000000000000
-
1888 发帖7917 回复34980 积分
- 私信他 +关注
-
- xiaomiking
-
1147 发帖6357 回复18609 积分
- 私信他 +关注
块
导
航
举报
请选择举报类别
- 广告垃圾
- 违规内容
- 恶意灌水
- 重复发帖