[分享] Python Pandas之学习(Lesson_3)
532 查看
4 回复
 楼主 | 发布于 2018-04-15 | 只看楼主
分享到:

使用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)

输出结果:

(0 ) (0 )
回复 举报

楼主 | 回复于 2018-04-15 沙发

好像最后的数据图像没有能添加进去。

(0 )
评论 (0) 举报

回复于 2018-04-15 2#

感谢分享;
(0 )
评论 (0) 举报

回复于 2018-04-16 3#

多谢分享!!!
(0 )
评论 (0) 举报

回复于 2018-04-17 4#

谢谢分享!!!
(0 )
评论 (0) 举报
  • 发表回复
    0/3000





    举报

    请选择举报类别

    • 广告垃圾
    • 违规内容
    • 恶意灌水
    • 重复发帖

    全部板块

    返回顶部