用Python做数据分析初探(三)

来源:互联网 发布:查询统计不重复的数据 编辑:程序博客网 时间:2024/05/21 05:38

准备数据

开发环境已经准备好了, 接下来我们可以用 Numpy , Pandas 等工具做数据分析了。 但数据源到哪里找呢? 我首先想到的是磁盘文件。 这么多年来,一直不清楚自己的HOME目录为什么这么大,有哪些大文件是最占空间的,哪些文件是很久不用的,现在终于可以分析一下了。

首先写个简单的 Python 程序,把目录里的所有文件都列出来,保存成一个文本文件:

#! /usr/bin/env python# -*- coding: utf-8 -*-# Yuwen Dai  15 June, 2017# list all files in a direcotry, result is a table:# ((file_name1, size, created_time, access_time),#  (file_name2, size, created_time, access_time),#  ...)def create_table(table, dir, files):    for name in files:        full = os.path.join(dir, name) # get the full name        # we need size, create date, access date information        # add it to the table        if not os.path.isdir(full) and not os.path.islink(full):            st = os.stat(full)            table.append([full, st[stat.ST_SIZE], st[stat.ST_CTIME], st[stat.ST_ATIME]])def print_table_csv(table):    for line in table:        print '\t'.join(map(str, line))if __name__ == '__main__':    import sys,os,stat    table = []    os.path.walk(sys.argv[1], create_table, table)    print_table_csv(table)

这个程序的核心是调用 os.path.walk 遍历某个目录,把文件的名称、大小、创建时间和存取时间打印出来。 指定一个目录名,运行该程序:

./list_files.py  /home/yuwen/doc  > file_table2.txtwc -l file_table2.tx7687 file_table2.txt

不错, 这个文件有7687行,说明有7687个文件,数量还是蛮多的。 它的内容是这样的:

file_list

每行是一个文件的信息,包括文件名、尺寸、创建时间、存取时间。 注意时间是秒数,并不是我们能认出来的ASCII time。 这样比较时间的早晚很方便。

有了这个表格,我们就可以用 Pandas 读入了。 打开 Juypter Notebook,输入:

import osimport pandas as pd

shift+enter 执行, 如果没有出错,继续在下一个cell 里输入:

file = pd.read_csv("file_table2.txt", sep='\t')file.columns = ['name','size','create_date', 'access_date']

我们用 Pandas 的 read_csv 函数读取文件,并指定了列的名称。看一下生成的表格:
table

看上去一切正常,符合预期。接下来我们就可以利用这个表格做一些探索了。