Python数据分析基础 (1)python基础

一.数及函数

1.标准模块 math

exp、log 和 sqrt

exp、log 和 sqrt 分别表示 e 的乘方、自然对数和平方根。
math函数

其他函数

type(varible) 会返回 Python 中的数据类型。

.format()

a = [1, 2, 3, 4]
b = ["first", "second", "third", "fourth"]
c = a + b
print("Output #3: {0}, {1}, {2}".format(a, b, c))
x = 4
y = 5
z = x + y
print("Output #2: Four plus five equals {0:d}.".format(z))

二.字符串及函数

当你使用 3 个单引号或 3 个双引号时,不需要在前面一行的末尾加上反斜杠。

反斜杠将一个非常长的字符串分段显示在多个行中,以使它易于理解和编辑。尽管这个字符串分布在脚本的多个行中,它还是一个字符串,并作为一个完整的字符串被打印出来。在这种将长字符串分成多行的方法中,要注意的是反斜杠必须是每行的最后一个字符。如果你意外地按了一下空格键,反斜杠后面就会出现一个看不见的空格,脚本就会抛出一个语法错误,不能正常运行。

+、* 和 len

处理字符串的一个常用标准库模块是 string。

模块string

1.split

将一个字符串拆分成一个子字符串列表,列
表中的子字符串正好可以构成原字符串。

split 函数可以在括号中使用两个附加参数。第一个附加参数表示使用哪个字符进行拆分。第二个附加参数表示进行拆分的次数

2. join

join 函数将列表中的子字符串组合成一个字符串。join 函数
将一个参数放在 join 前面

3. strip

lstrip、rstrip 和 strip 函数分别从字符串的左侧、右侧和两
侧删除空格、制表符和换行符
从字符串两端删除其他字符的方法,将这些字符作为 strip 函数的附加
参数即可。

string4 = "$$The unwanted characters have been removed.__---++"
string4_strip = string4.strip('$_-+')
print("Output #31: {0:s}".format(string4_strip))

4. replace

下面两个示例展示了如何为另一个或
另一组字符。这个函数在括号中使用两个附加参数,第一个参数是要在字符串中查找替换
的字符或一组字符,第二个参数是要用来替换掉第一个参数的字符或一组字符:
replace(要替换的参数,将替换的函数)

5.lower 和 upper 和 capitalize

lower 和 upper 函数分别用来将字符串中的字母转换为小写和大写。capitalize 函数对字符串中的第一个字母应用upper 函数,对其余的字母应用 lower 函数

三.正则表达式与模式匹配

re 模块

# 计算字符串中模式出现的次数
string = "The quick brown fox jumps over the lazy dog."
string_list = string.split()
pattern = re.compile(r"The", re.I)
count = 0
for word in string_list:
 if pattern.search(word):
 count += 1
print("Output #38: {0:d}".format(count))

元字符

元字符

元字符包括 |、()、[]、.、*、+、?、^、
$ 和 (?P)

创建一个名为 pattern的正则表达式

pattern = re.compile(r"The", re.I)

re.compile

函数将文本形式的模式编译成为编译后的正则表达式。

re.I

函数确保模式是不区分大小写的
能同时在字符串中匹配“The”和“the”。

原始字符串标志 r

可以确保 Python 不处理字符串中的转义字符,比如 \、\t 或 \n。
字符串中的转义字符和正则表达式中的元字符就不会有意外的冲突。

re.search

函数将列表中的每个单词与正则表达式进行比较。

string = "The quick brown fox jumps over the lazy dog."
string_list = string.split()
pattern = re.compile(r"(?P<match_word>The)", re.I)</match_word>
print("Output #39:")
for word in string_list:
 if pattern.search(word):
 print("{:s}".format(pattern.search(word).group('match_word')
# 在字符串中每次找到模式时将其打印出来
string = "The quick brown fox jumps over the lazy dog."
string_list = string.split()
pattern = re.compile(r"(?P<match_word>The)", re.I)</match_word>
print("Output #39:")
for word in string_list:
 if pattern.search(word):
 print("{:s}".format(pattern.search(word).group('match_word')
(?P <name>)

这是一个出现在 re.compile 函数中的元字符。这个元字符使匹配的字符串可以在后面的程序中通过组名符号 来引用。

re.sub 函数

来在文本中用一种模式替换另一种模式。

四.日期

datetime 模块

常用的对象和函数包括 today、year、month、day、timedelta、strftime 和 strptime。

#!/usr/bin/env python3
from math import exp, log, sqrt
import re
from datetime import date, time, datetime, timedelta
# 打印出今天的日期形式,以及年、月、日
today = date.today()
print("Output #41: today: {0!s}".format(today))
print("Output #42: {0!s}".format(today.year))
print("Output #43: {0!s}".format(today.month))
print("Output #44: {0!s}".format(today.day))
current_datetime = datetime.today()
print("Output #45: {0!s}".format(current_datetime))

通过使用 date.today(),你可以创建一个 date 对象,其中包含了年、月、日,但不包含时间元素

通过 datetime.today() 创建的对象则包含时间元素。

!s

!s 表示传入到 print 语句中的值应该格式化为字符串,尽管它是个数值型数
据。最后,你可以使用 year、month 和 day 来捕获具体的日期元素。

# 使用timedelta计算一个新日期
one_day = timedelta(days=-1)
yesterday = today + one_day
print("Output #46: yesterday: {0!s}".format(yesterday))
eight_hours = timedelta(hours=-8)
print("Output #47: {0!s} {1!s}".format(eight_hours.days, eight_hours.seconds)) 

在这个示例中,使用 timedelta 函数从今天减去了 1 天。当然,还可以在括号中使用days=10、hours=-8 或者 weeks=2 来创建变量,分别表示未来 10天、以前 8 个小时或者未来 2 个星期。

在使用 timedelta 时需要注意的一点是,它将括号中的时间差以天、秒和毫秒的形式存
储,然后将数值规范化后得到一个唯一的值。这说明分钟、小时和星期会被分别转换成 60
秒、3600 秒和 7 天,然后规范化,就是生成天、秒和毫秒“列”(类似于小学数学中的个
位、十位 等等)。举例来说,hours=-8 的输出是 (-1 days, 57,600 seconds),不是更简单
的 (-28,800 seconds)。是这样计算的:86 400 秒(3600 秒每小时 *24 小时每天)-28 800
秒(3600 秒每小时 *8 小时)= 57 600 秒。正如你所见,对负值的规范化乍看上去很令人
吃惊,特别是在进行取整和舍入时。

# 计算出两个日期之间的天数
date_diff = today - yesterday
print("Output #48: {0!s}".format(date_diff))
print("Output #49: {0!s}".format(str(date_diff).split()[0]))

示例展示了如何从一个 date 对象中减去另一个。相减的结果是个 datetime 对象,
将所得的差以天、小时、分钟和秒来显示。例如,在这个示例中结果是“1 day, 0:00:00”:

str 函数

可以将结果转换成字符串;

split 函数

可以使用空白字符将字符串拆分

# 根据一个日期对象创建具有特定格式的字符串
print("Output #50: {:s}".format(today.strftime('%m/%d/%Y')))
print("Output #51: {:s}".format(today.strftime('%b %d, %Y')))
print("Output #52: {:s}".format(today.strftime('%Y-%m-%d')))
print("Output #53: {:s}".format(today.strftime('%B %d, %Y')))

在我写这一章的时候,当天的 4 种打印形式如下:

01/28/2016
Jan 28, 2016
2016-01-28
January 28, 2016

格式符

包括 %Y、%B、%b、%m 和 %d。

五.列表

1.创建列表

将元素放在方括号之间就可以创建列表。

len 返回列表中元素的个数。min 和 max 分别返回列表中的最小值和最大值。count 返回列表中某个元素出现的次数。

2.索引值

列表尾部的索引值从-1 开始

3.列表切片

# 使用列表切片访问列表元素的一个子集
# 从开头开始切片,可以省略第1个索引值
# 一直切片到末尾,可以省略第2个索引值
print("Output #73: {}".format(a_list[0:2]))
print("Output #74: {}".format(another_list[:2]))
print("Output #75: {}".format(a_list[1:3]))
print("Output #76: {}".format(another_list[1:]

4.列表复制

# 使用[:]复制一个列表
a_new_list = a_list[:]
print("Output #77: {}".format(a_new_list))

5.列表连接

# 使用+将两个或更多个列表连接起来
a_longer_list = a_list + another_list
print("Output #78: {}".format(a_longer_list))

6. 使用in和not in

# 使用in和not in来检查列表中是否有特定元素
a = 2 in a_list
print("Output #79: {}".format(a))
if 2 in a_list:
 print("Output #80: 2 is in {}.".format(a_list))
b = 6 not in a_list
print("Output #81: {}".format(b))
if 6 not in a_list:
 print("Output #82: 6 is not in {}.".format(a_list))

列表操作

append 方法将一个新元素追加到列表末尾。
remove 方法可以删除列表中的任意元素。
pop 方法删除列表中的最后一个元素。

reverse 函数以 in-place 方式对列表进行反转的方法(原地反转)。“in-place”表示反转操作将原列表修改为顺序颠倒的新列表。

sort()对列表进行原地排序会修改原列表
要想对列表进行排序同时又不修改原列表,可以先复制列表

sorted排序函数

#!/usr/bin/env python3
from math import exp, log, sqrt
import re
from datetime import date, time, datetime, timedelta
from operator import itemgetter
my_lists = [[123,2,2,444], [22,6,6,444], [354,4,4,678], [236,5,5,678], \
[578,1,1,290], [461,1,1,290]]
my_lists_sorted_by_index_3_and_0 = sorted(my_lists, key=itemgetter(3,0))
print("Output #92: {}".format(my_lists_sorted_by_index_3_and_0))
# 使用sorted()对一个列表集合按照列表中某个位置的元素进行排序
Python基础 | 25
my_lists = [[1,2,3,4], [4,3,2,1], [2,4,1,3]]
my_lists_sorted_by_index_3 = sorted(my_lists, key=lambda index_value:\
index_value[3])
print("Output #91: {}".format(my_lists_sorted_by_index_3))

元组

创建元组

元组解包

元组转换成列表(及列表转换成元组)

要将一个列表转换成元组,将列表名称放在 tuple() 函数
中即可。
同样,要将一个元组转换成列表,将元组名称放在 list() 函数中即可。

字典

1. 创建字典

# 使用花括号创建字典
# 用冒号分隔键-值对
# 用len()计算出字典中键-值对的数量
empty_dict = { }
a_dict = {'one':1, 'two':2, 'three':3}
print("Output #102: {}".format(a_dict))
print("Output #103: a_dict has {!s} elements".format(len(a_dict)))
another_dict = {'x':'printer', 'y':5, 'z':['star', 'circle', 9]}
print("Output #104: {}".format(another_dict))
print("Output #105: another_dict also has {!s} elements"\
.format(len(another_dict)))

2. 引用字典中的值

# 使用键来引用字典中特定的值
print("Output #106: {}".format(a_dict['two']))
print("Output #107: {}".format(another_dict['z']

要引用字典中一个特定的值,需要使用字典名称、一对方括号和一个特定的键值(一个字符串)。在这个示例中,a_dict[‘two’] 的结果是整数2,another_dict[‘z’] 的结果是列表[‘star’, ‘circle’, 9]。

3. 复制

# 使用copy()复制一个字典
a_new_dict = a_dict.copy()
print("Output #108: {}".format(a_new_dict))

4. 键、值和项目

# 使用keys()、values()和items()
# 分别引用字典中的键、值和键-值对
print("Output #109: {}".format(a_dict.keys()))
a_dict_keys = a_dict.keys()
print("Output #110: {}".format(a_dict_keys))
print("Output #111: {}".format(a_dict.values()))
print("Output #112: {}".format(a_dict.items()))

要引用字典的键值,在字典名称后面加上 keys 函数即可。这个表达式的结果是包含字典键值的一个列表。

要引用字典值,在字典名称后面加上 values 函数即可。这个表达式的结果
是包含字典值的一个列表。

要想同时引用字典的键和值,在字典名称后面加上 items 函数即可。结果是一个列表,其中包含的是键-值对形式的元组。例如,a_dict.items() 的结果是 [(‘three’, 3), (‘two’,2), (‘one’, 1)]。

5. 使用in、not in和get

if ‘y’ in another_dict:

print(“Output #117: {!s}”.format(a_dict.get(‘four’)))
print(“Output #118: {!s}”.format(a_dict.get(‘four’, ‘Not in dict’)))

6. 排序

ordered_dict2 = sorted(dict_copy.items(), key=lambda item: item[1])
ordered_dict3 = sorted(dict_copy.items(), key=lambda x: x[1],reverse=True)
reverse=True 对应降序

控制流

1. if-else

2. if-elif-else

3. for循环

for i in range(len(z))

4. 简化for循环:列表、集合与字典生成式

# 使用列表生成式选择特定的行
my_data = [[1,2,3], [4,5,6], [7,8,9]]
rows_to_keep = [row for row in my_data if row[2] > 5]
print("Output #130 (list comprehension): {}".format(rows_to_keep)
# 使用集合生成式在列表中选择出一组唯一的元组
my_data = [(1,2,3), (4,5,6), (7,8,9), (7,8,9)]
set_of_tuples1 = {x for x in my_data}
print("Output #131 (set comprehension): {}".format(set_of_tuples1))
set_of_tuples2 = set(my_data)
print("Output #132 (set function): {}".format(set_of_tuples2))

5. while循环

6. 函数

要在 Python 中创建函数,需要使用 def 关键字

7. 异常

常用的异常包括 IOError、IndexError、KeyError、NameError、SyntaxError、TypeError、UnicodeError 和 ValueError。

8. try-except

# 计算一系列数值的均值
def getMean(numericValues):
 return sum(numericValues)/len(numericValues)
my_list2 = [ ]
# 简单形式
try:
 print("Output #138: {}".format(getMean(my_list2)))
except ZeroDivisionError as detail:
 print("Output #138 (Error): {}".format(float('nan')))
 print("Output #138 (Error): {}".format(detail))

except 代码块来处理潜在的错误并打印出错误信息来帮助你理解程序错误

9. try-except-else-finally

# 完整形式
try:
 result = getMean(my_list2)
except ZeroDivisionError as detail:
 print "Output #142 (Error): " + str(float('nan'))
 print "Output #142 (Error):", detail
else:
 print "Output #142 (The mean is):", result
finally:
 print "Output #142 (Finally): The finally block is executed every time"

读取文本文件

sys 模块

导入了 sys 模块之后,你就可以使用 argv 这个列表变量了。

from math import exp, log, sqrt
import re
from datetime import date, time, datetime, timedelta
from operator import itemgetter
import sys
# 读取单个文本文件
input_file = sys.argv[1]
print("Output #143: ")
filereader = open(input_file, 'r')
for row in filereader:
	print(row.strip())
filereader.close()

在这里插入图片描述

如果文本文件和脚本不在同一位置,就需要输入文本文件的完整路径名,这样脚本才能知道去哪里寻找这个文件。

python first_script.py “C:\Users[Your Name]\Documents\file_to_read.txt”

读取文件的新型语法with

input_file = sys.argv[1]
print("Output #144:")
with open(input_file, 'r', newline='') as filereader:
for row in filereader:
 print("{}".format(row.strip()))

使用glob读取多个文本文件

导入内置的 os 模块和 glob 模块

例如,os.path.join函数可以巧妙地将一个或多个路径成分连接在一起。glob 模块可以找出与特定模式相匹配的所有路径名。os 模块和 glob 模块组合在一起使用,可以找出符合特定模式的某个文件夹下面的所有文件

print("Output #145:")
inputPath = sys.argv[1]
for input_file in glob.glob(os.path.join(inputPath,'*.txt')):
 with open(input_file, 'r', newline='') as filereader:
 for row in filereader:
 print("{}".format(row.strip()))

os.path.join 函数将这个文件夹路径和这个文件夹中所有符合特
定模式的文件名连接起来,这种特定模式可以由 glob.glob 函数扩展。这个示例使用的是模式 *.txt 来匹配由 .txt 结尾的所有文件名。

写入文本文件

my_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
max_index = len(my_letters)
output_file = sys.argv[1]
filewriter = open(output_file, 'w')
for index_value in range(len(my_letters)):
 if index_value < (max_index-1):
 filewriter.write(my_letters[index_value]+'\t')
 else:
 filewriter.write(my_letters[index_value]+'\n')
filewriter.close()
print "Output #146: Output written to file"

写入CSV文件

要向文本文件中追加数据,输入以下命令然后按回车键:
python first_script.py “C:\Users[Your Name]\Desktop\write_to_file.txt”

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值