本文参考Paul Barry所著的《Head First Python》一书,参考代码均可由http://python.itcarlow.ie/站点下载。本文若有任何谬误希望不吝赐教~

二. 代码模块
 
1. 准备学习
 
(1)数据读取
with open(james.txt) as jaf: #打开文件
    data = jaf.readline() #读数据行
 james =data.strip().split(',') #将数据转换为列表
 

说明:data.strip().split(',')叫做方法串链,strip()应用到data中的数据行,去除字符串中所有的空白符,处理后的结果由第二个方法split(',')处理,split(',')表示将结果以,形式分割开,返回列表。

 
(2)数据清理
定义函数sanitize(),将各个选手成绩的列表格式统一为mins.secs格式
def sanitize(time_string):
    if '-' in time_string:
        splitter = '-'
    if ':' in time_string:
        splitter = ':'
    else:
        return(time_string)
(mins,secs) = time_string.split(splitter)
return(mins + '.' + secs)
 
说明:split是内置函数,表示字符串的分解
 
(3) 转换列表---推导列表
分别举例普通列表转换方法与利用推导列表的方式:
clean_mikey = [] #列表创建
for each_t in mikey: #迭代
    clean_mikey.append(sanitize(each_t)) #转换与追加

等价于

clean_mikey = [sanitize(each_t) for each_t in mikey]
 
说明:sanitize()为自定义的一个数据清理函数,内置函数sorted是对整个列表排序
 
(4) 删除重复数据--not in
列表操作方法:
unique_james = []
for each_t in james:
    if each_t not in unique_james:
        unique_james.append(each_t)
集合操作方法:(python集合突出特点,就是集合中数据项的无序性,且不允许重复)
示例: 
distances = set(james)
 
(5)“分片”,访问列表中多个列表项

print(sorted(set([sanitize(t)] for t in james]))[0:3])

 

(6)将多个重复代码改为函数

def get_coach_data(filename):
    try:
        with open(filename) as af:
            return(data.strip().split(','))
    except IOError as ioerr:
        print('File error:' + str(ioerr))
        return(None)
 
2. 定制数据对象
 
(1)新数据格式,James2.txt,Julie2.txt,Mikey2.txt,Sarah2.txt,文件分别打开如下:(全名, 出生日期, 训练成绩)
James Lee,2002-3-14,2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22,2-01,2.01,2:16
Julie Jones,2002-8-17,2.59,2.11,2:11,2:23,3-10,2-23,3:10,3.21,3-21,3.01,3.02,2:59
Sarah Sweeney,2002-6-17,2:58,2.58,2:39,2-25,2-55,2:54,2.18,2:55,2:55,2:22,2-21,2.22
Mikey McManus,2002-2-24,2:22,3.01,3:01,3.02,3:02,3.02,3:22,2.49,2:38,2:40,2.22,2-31
 
(2)数据抽取:(以Sarah为例)
Sarah = get_coach_data('sarah2.txt')
(sarah_name,sarah_dob) = sarah.pop(0),sarah.pop(0)
pop(0)调用将删除并返回列表最前面的数据项,并赋值给指定变量姓名和出生日期
 
(3)使用字典关联数据,字典是一种内置的数据结构,允许将数据和键而不是数字关联,这样可以使内存中的数据与实际数据的结构保持一致。
比如,键                   关联的数据
        Name     ——> Sarah Sweeney
        DOB      ——> 2002-6-17
        Times    ——> 2:58,2.58,2:39,2-25,2-55,2:54,2.18,2:55,2:55,2:22,2-21,2.22
创建字典的方式:
          大括号创建:cleese = {}
          工厂函数:   palin = dict()
增加数据两种方式:
          cleese['Name'] = 'John Cleese'
          palin = {'Name': 'Michael Palin'}
 
(4)应用:
        sarah_data = {}
        sarah_data['Name'] = sarah.pop(0)
        sarah_data['DOB'] = sarah.pop(0)
        sarah_data['Times'] = sarah
        print(sarah_data['Name' + "'s fastest times are: " + str(sorted(set[sanitize(t) for t in sarah_data['Times']]))[0:3]))
 
(5)一次性完成字典的创建,并返回字典
def get_coach_data(filename):
    try:
        with open(filename) as f:
            data = f.readline()
        templ = data.strip().split(',')
        return({'Name':templ.pop(0),
                    'DOB':templ.pop(0),
                     'Times':str(sorted(set([sanitize(t) for t in templ]))[0:3])})
    except IOError as ioerr:
        print('File error:' + str(ioerr))
        return(None)
 
(6)将代码及其数据打包在类中
class Athlete:
    def __init__(self,a_name,a_dob,a_times=[]):
        self.name = a_name
        self.dob=a_dob
        self.times=a_times
   
   def top3(self):
       return(sorted(set([sanitize(t) for t in self.times]))[0:3])
   
   def get_coach_data(filename):
       try:
        with open(filename) as f:
            data = f.readline()
        templ = data.strip().split(',')
        return(Athlete(templ.pop(0),templ.pop(0),templ)
     except IOError as ioerr:
        print('File error:' + str(ioerr))
        return(None)
 

(7)类调用与结果输出

james = get_coach_data('james2.txt')
结果输出:
James Lee's fastest times are: ['2.01','2.16','2.22']
 
下一节课讲类的继承

Python的数据处理学习(二)的更多相关文章

  1. Python入门基础学习 二

    Python入门基础学习 二 猜数字小游戏进阶版 修改建议: 猜错的时候程序可以给出提示,告诉用户猜测的数字偏大还是偏小: 没运行一次程序只能猜测一次,应该提供多次机会给用户猜测: 每次运行程序,答案 ...

  2. Python的数据处理学习(三)

    三.类的继承   Python 的class可以允许从零开始创建一个定制类,就像文章(二)创建Athlete类一样,也可以通过继承现有的其他类类创建一个类,这也包括用List.set和dict提供的p ...

  3. python flask框架学习(二)——第一个flask程序

    第一个flask程序 学习自:知了课堂Python Flask框架——全栈开发 1.用pycharm新建一个flask项目 2.运行程序 from flask import Flask # 创建一个F ...

  4. Python - 3.6 学习二

    Python 的高级特性 切片 对于指定索引范围取值的操作,Python提供了slice方法,类似于Excel中数据透视表的切片器. >>> L = ['Michael', 'Sar ...

  5. python数据处理技巧二

    python数据处理技巧二(掌控时间) 首先简单说下关于时间的介绍其中重点是时间戳的处理,时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00 ...

  6. Python学习二:词典基础详解

    作者:NiceCui 本文谢绝转载,如需转载需征得作者本人同意,谢谢. 本文链接:http://www.cnblogs.com/NiceCui/p/7862377.html 邮箱:moyi@moyib ...

  7. python --- 字符编码学习小结(二)

    距离上一篇的python --- 字符编码学习小结(一)已经过去2年了,2年的时间里,确实也遇到了各种各样的字符编码问题,也能解决,但是每次都是把所有的方法都试一遍,然后终于正常.这种方法显然是不科学 ...

  8. Python基础学习二

    Python基础学习二 1.编码 utf-8编码:自动将英文保存为1个字符,中文3个字符.ASCll编码被囊括在内. unicode:将所有字符保存为2给字符,容纳了世界上所有的编码. 2.字符串内置 ...

  9. python 数据处理学习pandas之DataFrame

    请原谅没有一次写完,本文是自己学习过程中的记录,完善pandas的学习知识,对于现有网上资料的缺少和利用python进行数据分析这本书部分知识的过时,只好以记录的形势来写这篇文章.最如果后续工作定下来 ...

随机推荐

  1. 别在细节上栽跟头------------mysql 字段类型详解

    也许你平时不在意,在设计数据库的时候,数字就设成int(10) 字符串就设成varchar(20)或者text 普通情况下是没有问题的,但是若不理解字段类型和长度的含义,总有一天你会在这里栽跟头, 这 ...

  2. @Factory和@DataProvider的区别

    DataProvider: A test method that uses DataProvider will be executed a multiple number of times based ...

  3. kettle的jdk1.7环境变量配置

    1).到官网下载需要安装的kettle版本,目前最新版本4.2,官网地址:http://kettle.pentaho.org,我们是使用的版本是kettle3.2 2).本地安装jdk 1.4或以上版 ...

  4. Volley HTTP库系列教程(2)Volley.newRequestQueue示例,发请求的流程,取消请求

    Sending a Simple Request Previous  Next This lesson teaches you to Add the INTERNET Permission Use n ...

  5. Android无法访问本地服务器(localhost)的解决方案

    在Android开发中通过localhost或127.0.0.1访问本地服务器时,会报java.net.ConnectException: localhost/127.0.0.1:8083 -Conn ...

  6. Android之项目推荐使用的第三方库

    1. 使用上拉更多,下拉刷新:https://github.com/JosephPeng/XListView-Android 这个是github上面更为火爆的:https://github.com/c ...

  7. typedef struct trx_struct trx_t;

    /* The transaction handle; every session has a trx object which is freed only when the session is fr ...

  8. 用Access作为后台数据库支撑,书写一个C#写入记录的案例

    要想操作一个数据库,不论是那种操作,首先要做的肯定是打开数据库. 下面我们以ACCESS数据库来做例子说明如何打开一个数据库连接!   在这里我们需要用到的是: System.Data.OleDb.O ...

  9. 51nod1202 子序列个数

    看到a[i]<=100000觉得应该从这个方面搞.如果a[x]没出现过,f[x]=f[x-1]*2;否则f[x]=f[x-1]*2-f[pos[a[x]]-1];ans=f[n]-1,然后WA了 ...

  10. POJ 2125 Destroying The Graph (二分图最小点权覆盖集+输出最小割方案)

    题意 有一个图, 两种操作,一种是删除某点的所有出边,一种是删除某点的所有入边,各个点的不同操作分别有一个花费,现在我们想把这个图的边都删除掉,需要的最小花费是多少. 思路 很明显的二分图最小点权覆盖 ...