Python数据分析
发表于:2024-04-29 |

Python

一、基础语法

标识符

  1. 第一个字符必须是字母表中字母或者下划线_。
  2. 标识符的其他的部分由字母、数字和下划线组成。
  3. 标识符对大小写敏感。
  4. 在Python3中,可以用中文作为变量名,非ASCII标识符也是允许的。

保留字

1
2
3
4
5
6
7
False      await      else       import     pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

注释

  1. python中单行注释用#开头
  2. 多行注释可以用多个#号开头,还有'''"""
1
2
3
4
5
6
7
8
9
# 注释一
'''
注释二
'''

"""
注释三

"""

行与缩进

  1. python最具特色的就是使用缩进来表示代码块,不需要使用大括号{}
  2. 缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进空格数。实例如下:
1
2
3
4
5
6
if a==1:
print(a)
print("Ture")
print("a是等于1的",end=" ")

print("Go!")

输入和输出

  1. print默认输出是换行的,如果需要实现不换行需要在变量末尾加上end="":
  2. input用的比较少(读入的是字符串类型)

二、基本数据类型

  1. python中的变量不需要声明,每个变量在使用之前必须赋值,变量赋值以后该变量才会被创建
  2. 在python中,变量就是变量,它没有类型,我们所说的“类型”是变量所指的内存中对象的类型
  3. 等号(=)用来给变量赋值
  4. 等号(=)运算符左边是一个变量名,等号(=)运算符右边是存储在变量中的值

常见的数据类型

1
2
3
4
5
6
7
8
9
10
counter = 100
# 整数型
miles = 2.13
# 浮点型
flag = True
# 布尔型
name = "run"
# 字符串
print(type(a)) #type查看类型
f = 1+2j #复数类型 complex

数据类型转换

  1. 隐式类型转换——自动完成
  2. 显式类型转换——需要使用类型函数来转换
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#数据类型转换
a = 100
b = 12.45
print(a + b) #112.45
print(type(a),type(b),type(a + b)) #int float float
#c = a + int(b)
c = int(a + b)
print(type(a),type(b),type(c)) #int float int
print(c) #112
d = '0'
ad = a + int(d)
print(type(a),type(d),type(ad)) #int str int
print(ad) #100
da = str(a) + d
print(type(a),type(d),type(da)) #int str str
print(da) #1000

三、字符串基本操作

字符串是由字符组成的序列,可以使用单引号(’’)或双引号(“”)括起来。字符串中每一个字符都有索引,可以使用索引来访问特定位置的序列。索引都是从0开始的。

切片是指通过指定起始索引和结束索引来提取子字符串。例如:print(name[1:3])将输出”li”,其中name=”Alice”,输出的字符长度为结束索引减去起始索引,不包括结束索引的字符。当索引为负数时,则从后面往前面开始遍历字符串,即-1对应字符串最后一个字符,-2对应字符串倒数第二个字符……

拼接:使用+号可以将两个字符串拼接在一起,例如:greeting=”Hello” + name

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#字符串基本操作
name = "Alice"

#索引
print(name[0]) #A
print(name[4]) #e
print(name[1:3]) #li
print(name[1:2]) #l
print(name[-1]) #e
print(name[-4:-2]) #li
#结束索引减去起始索引

#拼接
test = "Hello" + name
print(test)
print(test + " " + name)
print("123" * 4) #字符串重复四次
print(name[-4:-2] * 2 + name[1:3]) #lilili

四、运算符

算数运算符

运算符 描述 示例
+ 加法 3 + 4 = 7
- 减法 7 - 3 = 4
* 乘法 3 * 4 = 12
/ 除法 7 / 3 = 2.33333…
// 整除 7 // 3 = 2
% 取模 7 % 3 = 1
** 指数 2 ** 3 = 8
1
2
3
4
5
6
7
8
9
10
x = 10
y = 3

print(x + y) # 输出 13
print(x - y) # 输出 7
print(x * y) # 输出 30
print(x / y) # 输出 3.3333333333333335
print(x // y) # 输出 3
print(x % y) # 输出 1
print(x ** y) # 输出 1000

赋值运算符

赋值运算符用于给变量或者表达式赋值。Python支持多种赋值运算符,包括简单赋值、加等于赋值、减等于赋值、乘等于赋值、除等于赋值、取模等于赋值、幂等于赋值、整除等于赋值等。

以下是一些常见的赋值运算符及其使用方法:

  • 简单赋值运算符(=):用于将一个值赋给变量。
  • 加等于赋值运算符(+=):用于将右边的值加到左边的变量上,并将结果赋给左边的变量。
  • 减等于赋值运算符(-=):用于将右边的值减去左边的变量,并将结果赋给左边的变量。
  • 乘等于赋值运算符(*=):用于将右边的值乘以左边的变量,并将结果赋给左边的变量。
  • 除等于赋值运算符(/=):用于将左边的变量除以右边的值,并将结果赋给左边的变量。
  • 取模等于赋值运算符(%=):用于将左边的变量对右边的值取模,并将结果赋给左边的变量。
  • 幂等于赋值运算符(**=):用于将左边的变量幂运算右边的值,并将结果赋给左边的变量。
  • 整除等于赋值运算符(//=):用于将左边的变量整除右边的值,并将结果赋给左边的变量。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
a = 10   # 简单赋值
print(a)
a += 5 # 加等于赋值,等同于 a = a + 5
print(a)
a -= 3 # 减等于赋值,等同于 a = a - 3
print(a)
a *= 2 # 乘等于赋值,等同于 a = a * 2
print(a)
a /= 4 # 除等于赋值,等同于 a = a / 4
print(a)
a **= 3 # 幂等于赋值,等同于 a = a ** 3
print(a)
a //= 2 # 整除等于赋值,等同于 a = a // 2
print(a)
a %= 2 # 取模等于赋值,等同于 a = a % 2
print(a)

比较运算符

比较运算符用于比较两个值,返回一个布尔值(True或False)。以下是Python支持的比较运算符:

  • 等于运算符(==):用于检查两个值是否相等,如果相等则返回 True,否则返回 False。
  • 不等于运算符(!=):用于检查两个值是否不相等,如果不相等则返回 True,否则返回 False。
  • 大于运算符(>):用于检查左侧的值是否大于右侧的值,如果是则返回 True,否则返回 False。
  • 小于运算符(<):用于检查左侧的值是否小于右侧的值,如果是则返回 True,否则返回 False。
  • 大于等于运算符(>=):用于检查左侧的值是否大于或等于右侧的值,如果是则返回 True,否则返回 False。
  • 小于等于运算符(<=):用于检查左侧的值是否小于或等于右侧的值,如果是则返回 True,否则返回 False。
1
2
3
4
5
6
7
8
9
x = 10
y = 3

print(x == y) # 输出 False
print(x != y) # 输出 True
print(x > y) # 输出 True
print(x < y) # 输出 False
print(x >= y) # 输出 True
print(x <= y) # 输出 False

逻辑运算符

逻辑运算符用于比较两个或多个表达式的布尔值,并返回一个布尔值(True或False)。以下是Python支持的逻辑运算符:

  • 逻辑与运算符(and):用于检查两个表达式是否都为True。
  • 逻辑或运算符(or):用于检查两个表达式是否至少有一个为True。
  • 逻辑非运算符(not):用于对表达式的值取反,如果条件为假,则返回 True,否则返回 False。
1
2
3
4
5
6
7
x = 5
y = 3
z = 7

print(x > y and z > x) # 输出 True
print(x < y or z < x) # 输出 False
print(not x < y) # 输出 True

逻辑运算符的优先级与数学中的运算符优先级不同,需要使用括号来明确优先级。例如,(x > y) and (z > x)x > y and z > x 的结果是不同的。

位运算符

位运算符是用于对二进制数进行操作的运算符,包括按位与、按位或、按位异或、按位取反等,适用于整数类型数据。下面是Python中的位运算符:

  • 按位与运算符(&):参与运算的两个数,对应的二进制位上如果都是1,结果为1,否则为0。
  • 按位或运算符(|):参与运算的两个数,对应的二进制位上如果有一个是1,结果为1,否则为0。
  • 按位异或运算符(^):参与运算的两个数,对应的二进制位上如果只有一个是1,结果为1,否则为0。
  • 按位取反运算符(~):对参与运算的数的二进制位按位取反,0变为1,1变为0。
  • 左移运算符(<<):将参与运算的数的二进制位向左移动指定的位数,左移后低位补0。
  • 右移运算符(>>):将参与运算的数的二进制位向右移动指定的位数,右移后高位补0或补1(取决于参与运算的数的符号位)。
1
2
3
4
5
6
7
8
9
a = 60
b = 13

print(a & b) # 输出12
print(a | b) # 输出61
print(a ^ b) # 输出49
print(~a) # 输出-61
print(a << 2) # 输出240
print(a >> 2) # 输出15

成员运算符

成员运算符用于测试一个值是否在序列中出现。常用的成员运算符有 innot in

  • in:用于判断一个值是否是一个序列的成员,是返回True,否则返回False
  • not in:用于判断一个值是否不是一个序列的成员,不是返回True,否则返回False
1
2
3
4
a = [1, 2, 3, 4, 5]

print(3 in a) # 输出True
print(6 not in a) # 输出True

身份运算符

身份运算符用于比较两个对象的存储单元,返回布尔值 TrueFalse

以下是 Python 中的身份运算符:

  • is :判断两个对象是否引用同一存储单元,如果是则返回 True,否则返回 False
  • is not :判断两个对象是否引用不同的存储单元,如果是则返回 True,否则返回 False
1
2
3
4
5
6
7
a = 5
b = 5
print(a is b) # 输出True

c = [1, 2, 3]
d = [1, 2, 3]
print(c is d) # 输出False

运算符优先级

在Python中,不同的运算符有不同的优先级,当表达式中含有多个运算符时,Python会按照一定的优先级进行计算。常见运算符的优先级从高到低如下:

运算符 描述
** 指数运算(最高优先级)
+x, -x, ~x 正、负、按位取反运算
*, /, //, % 乘、除、整除、取模运算
+, - 加、减运算
<<, >> 按位左移、按位右移运算
& 按位与运算
^ 按位异或运算
| 按位或运算
==, !=, >, >=, <, <= 比较运算符和成员运算符(左侧优先)
=, +=, -=, *=, /=, //=, %=, **= 赋值运算符和增量赋值运算符(从右向左结合)
is, is not 身份运算符
in, not in 成员运算符
not 逻辑非运算符
and 逻辑与运算符
or 逻辑或运算符
lambda lambda表达式(最低优先级)

五、复合数据类型

列表(List)

列表是一种有序的数据类型,可以存储多个任意类型的数据。列表使用方括号[ ]来表示,每个元素之间用逗号隔开。

创建列表

1
2
lst = [1, 2, 3, 'four', 'five']
print(type(lst), lst) #list类型

访问元素

列表的元素可以通过索引来访问,索引从0开始。列表还支持切片操作,可以使用类似于字符串的切片语法来访问其中的元素。

1
2
3
lst = [1, 2, 3, 'four', 'five']
print(lst[0]) #1
print(lst[1:3]) #[2,3]

内置方法

除了基本的访问和切片操作,列表还支持一系列的方法,列表有很多常用的方法,下面是一些常用的列表方法:

  • append():向列表末尾添加一个元素。
  • insert():向列表指定位置插入一个元素。
  • remove():从列表中移除指定的元素。
  • pop():从列表末尾移除一个元素。
  • sort():对列表进行排序。
  • reverse():将列表翻转。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
my_list = [1, 2, 3, 4, 5]
print("原始列表:", my_list)
# 添加一个元素
my_list.append(6)
print("添加一个元素:", my_list)
# 在指定位置插入一个元素
my_list.insert(2, "hello")
print("在指定位置插入一个元素:", my_list)
# 移除指定的元素
my_list.remove(4)
print("移除指定的元素:", my_list)
# 移除末尾的元素
my_list.pop()
print("移除末尾的元素:", my_list)
# 对列表进行排序
my_list.sort()
print("对列表进行排序:", my_list)
# 将列表翻转
my_list.reverse()
print("将列表翻转:", my_list)

列表操作

除了列表自身的一些方法外,Python还提供了一些方法可以操作列表:

  • len():求列表中元素的个数。
  • +:合并两个列表。
  • *:重复列表元素。
  • in:判断元素是否在列表内。
  • for:对列表进行遍历。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
my_list1 = [1, 2, 3]
my_list2 = ["A", "B", "C"]
print("原始列表1:", my_list1)
print("原始列表2:", my_list2)
# 求列表长度
ln = len(my_list1)
print("求列表长度:", ln)
# 合并两个列表
my_list3 = my_list1 + my_list2
print("合并两个列表:", my_list3)
# 重复列表元素
my_list4 = my_list1 * 3
print("重复列表元素:", my_list4)
# 判断元素是否在列表内
ex1 = 3 in my_list1
ex2 = 3 in my_list2
print("判断元素是否在列表内:", ex1, ex2)
# 对列表进行遍历
for x in my_list1:
print("对列表进行遍历:", x)

元组(Tuple)

元组和列表类似,也是一种有序的数据类型,可以存储多个任意类型的数据。但是元组一旦创建,就不能再修改其中的元素。

元组使用圆括号 ( ) 来表示,每个元素之间用逗号隔开。

创建元组

1
2
tuple1 = (1, 2, 3, 'four', 'five')
print(tuple1)

访问元素

元组的访问和切片操作和列表类似,也是通过索引和切片语法来实现。

1
2
3
4
5
6
7
8
9
10
tuple1 = (1, 2, 3, 'four', 'five')
tuple2 = ("A", "B", "C")
print("通过索引访问:", tuple1[2])
print("通过切片访问:", tuple1[1:3])
print("元组长度:", len(tuple1))
print("元素重复:", tuple1 * 3)
print("元组合并:", tuple1 + tuple2)
print("元素判断:", "A" in tuple1, "A" in tuple2)
for x in tuple2:
print("对元组进行遍历:", x)

集合(Set)

集合是一种无序、不重复的数据类型,用于去重或者判断一个元素是否存在。集合使用花括号 { } 来表示,每个元素之间用逗号隔开。

创建集合

1
2
set1 = {1, 2, 3, 'four', 'five'}
print(set1)

基本操作

集合的操作包括添加元素、删除元素、查找、遍历、求并集、交集等。

  • add(element):向集合中添加元素
  • update(set):向集合中添加多个元素,将集合更新为和指定集合的并集
  • discard(element):移除集合中指定的元素
  • remove(element):移除集合中指定的元素,如果不存在则抛出异常
  • pop():随机移除一个元素并返回,由于集合是无序的,因此无法确定删除的是哪个元素。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
my_set = {1, 2, 3}
# 添加不存在的元素
my_set.add(4)
print("添加不存在的元素:", my_set)
# 添加已经存在的元素
my_set.add(2)
print("添加已经存在的元素:", my_set)
# 向集合中添加多个元素
my_set.update([5, 6])
my_set.update((7, 8))
my_set.update({9, 10})
print("向集合中添加多个元素:", my_set)
# 移除集合中指定的元素
my_set.remove(3)
my_set.discard(5)
pp = my_set.pop()
print("移除集合中指定的元素:", my_set, pp)
for x in my_set:
print("遍历集合:", x)

其他操作

可以使用一些内置的方法来对集合进行操作。以下是一些常用的集合方法:

  • clear():清空集合
  • copy():复制集合
  • difference(set):返回集合和指定集合的差集
  • difference_update(set):移除集合中和指定集合相同的元素
  • intersection(set):返回集合和指定集合的交集
  • intersection_update(set):保留集合中和指定集合相同的元素
  • isdisjoint(set):判断两个集合是否没有共同元素
  • issubset(set):判断一个集合是否是另一个集合的子集
  • issuperset(set):判断一个集合是否是另一个集合的超集
  • symmetric_difference(set):返回集合和指定集合的对称差集
  • symmetric_difference_update(set):将集合更新为和指定集合的对称差集
    union(set):返回集合和指定集合的并集
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 创建集合
fruits = {"apple", "banana", "cherry"}
# 添加元素
fruits.add("orange")
print(fruits) # 输出: {'banana', 'apple', 'orange', 'cherry'}
# 移除元素
fruits.remove("banana")
print(fruits) # 输出: {'apple', 'orange', 'cherry'}
# 清空集合
fruits.clear()
print(fruits) # 输出: set()
# 复制集合
fruits = {"apple", "banana", "cherry"}
fruits_copy = fruits.copy()
print(fruits_copy) # 输出: {'banana', 'apple', 'cherry'}
# 求交集
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z) # 输出: {'apple'}
# 求并集
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.union(y)
print(z) # 输出: {'banana', 'apple', 'google', 'cherry', 'microsoft'}
# 判断是否是子集
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
z = x.issubset(y)
print(z) # 输出: True

字典(Dictionary)

字典是一种无序的键值对(key-value)数据类型,可以用来存储任意类型的数据。字典使用花括号 { } 来表示,每个键值对之间用冒号 : 隔开,键值对之间用逗号隔开。key必须是唯一的

创建字典

可以使用花括号 {} 或者 dict() 函数来创建字典。使用花括号创建字典时,键-值对之间用冒号 : 分隔,每个键-值对之间用逗号分隔

1
2
3
4
5
6
# 使用花括号创建字典
my_dict1 = {'apple': 3, 'banana': 5, 'orange': 2}
print(my_dict1)
# 使用 dict() 函数创建字典
my_dict2 = dict(apple=3, banana=5, orange=2)
print(my_dict2)

访问元素

可以使用键来访问字典中的元素。如果键不存在,则会抛出 KeyError 异常。

1
2
3
4
my_dict = {'apple': 3, 'banana': 5, 'orange': 2}

print(my_dict['apple']) # 输出 3
print(my_dict['pear']) # 抛出 KeyError 异常

可以使用 get() 方法来访问字典中的元素。如果键不存在,则会返回 None 或者指定的默认值。

1
2
3
4
5
my_dict = {'apple': 3, 'banana': 5, 'orange': 2}

print(my_dict.get('apple')) # 输出 3
print(my_dict.get('pear')) # 输出 None
print(my_dict.get('pear', 0)) # 输出 0

基本操作

Python字典包含了以下内置方法:

clear():删除字典内所有元素
copy():返回一个字典的浅复制
get(key, default=None):返回指定键的值,如果值不在字典中返回default值。
has_key(key):如果键在字典dict里返回true,否则返回false。
items():以列表返回可遍历的(键, 值) 元组数组。
keys():以列表返回一个字典所有的键。
values():以列表返回字典中的所有值。

六、条件语句和循环结构

条件语句

条件语句使用的是 if 关键字,在代码运行中,有时候需要在不同的情况下执行不同的内容,此时就需要使用if条件句。

语法结构:

1
2
3
4
5
6
7
if 表达式1:
执行的代码1
elif 表达式2:
执行的代码2
……
else:
执行的代码3

示例:

1
2
3
4
5
6
7
8
9
a = int(input('输入数字 a: '))
b = int(input('输入数字 b: '))

if a > b:
print(a)
elif a < b:
print(b)
else :
print("a和b相等")

三目运算符的使用

变量 = 表达式1 if 判断条件 else 表达式2,执行原理就是,当if判断条件成立的时候,执行表达式1的代码,否则执行表达式2的代码

1
2
3
4
5
6
a = int(input('输入数字 a: '))
b = int(input('输入数字 b: '))

max = a if a > b else b

print(max)

循环语句

while循环

while 循环的使用是非常简单的,只要判断条件为真就可以不断的循环下去

1
2
while 判断条件:
执行的代码

示例:

1
2
3
4
5
6
7
8
9
# 计算 1+2+3+……+100
i = 1
sum = 0

while i <= 100:
sum += i
i += 1
print(sum)

for循环

1
2
3
4
5
6
7
8
for 变量 in 字符串或可迭代对象:
执行的代码

这里介绍一下for循环的使用:
1、可迭代对象:可以是列表,字典,集合等.
2for 循环的使用规则是:每循环一次,变量就依次读取'可迭代对象或字符串'的一个元素
直到变量将'可迭代对象或字符串内的元素'全部读取完,此时循环结束

示例代码:

1
2
for i in 'Hello World':
print(i, end=' ')

range()函数的使用:
range() 函数通常结合for 循环使用,用来创建一定范围的数据,使循环的变量达到依次读取数据的效果。下面介绍一下函数的用法:

range(n) 创建[0,n)的数据,变量依次读取
range(n,m) 创建[n,m)的数据
range(n,m,t) 创建[n,m)的数据,但每个数之间的间隔时t

示例代码:

1
2
3
4
5
for i in 'HE':
print(f'{i}: ')
for j in range(4):
print(j, end=' ')
print('\n')
  • break :在循环过程中,当执行到break 关键字的时候会终止循环

  • continue :循环过程中,当执行到continue 关键字的时候,不会终止,但会跳过这一次循环

  • 循环 else 结构:此种结构是循环中的一种特殊结构,当for循环没有被break 关键字终止时,在循环结束后会执行else 内的代码,否则不会执行。

1
2
3
4
5
for 变量 in 字符串或可迭代对象:
执行的代码
else:
执行的代码

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
for i in 'Hello world':
if i == 'y':
print('字符串中包含字符 y')
break
else:
print('字符串中不包含字符 y')


print('==' * 8)
for i in 'Hello python':
if i == 'y':
print('字符串中包含字符 y')
break
else:
print('字符串中不包含字符 y')

'''
输出结果如下:

字符串中不包含字符 y
================
字符串中包含字符 y
'''

七、函数

函数定义

  1. 函数代码以def关键字开头,后接函数标识符名称和圆括号()
  2. 括号内部为函数的参数。
  3. 函数的第一行语句可以选择性地使用文档字符串——用于存放函数说明
  4. 函数内容以冒号:起始,并且缩进
  5. return[表达式]结束函数,选择性地返回一个值给调用方,不带表达式的return相当于返回None

如果在开发程序时,需要某块代码多次,但是为了提高编写的效率以及代码的重用,所以把具有独立功能的代码块组织为一个小模块,这就是函数

定义函数的格式如下

1
2
def 函数名():
代码

Python 使用def 开始函数定义,紧接着是函数名,内部为函数的具体功能实现代码

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def max(a,b=1):	#缺省参数,未传b时则b默认为1
if a>b :
return a
else :
return b

def printf(n):
print("要输出的数为:" + str(n))
return
a = int(input("输入的第一个数:"))
b = int(input("输入的第一个数:"))
maxn = max(a,b)
printf(maxn)

'''
输入:
a = 3
b = 2

输出结果为:
输入的第一个数:3
输入的第一个数:2
要输出的数为:3

'''

八、文件操作

打开一个文件

  1. Python open()方法用于打开一个文件,并返回文件对象
  2. 在对文件进行处理过程都需要使用到这个函数,如果该文件无法被打开,会抛出OSError
  3. 注意:使用open()方法一定要保证关闭文件对象,即调用close()方法
  4. open()函数常用形式是接收两个参数:文件名(file)和模式(model)
r 以只读方式打开文件,文件的指针将会放在文件的开头。这是默认模式。
r+ 打开一个文件用于读写。文件指针将会放在文件的开头。
w 打开一个文件只用于写入。如果该文件已存在则打开文件,并从头开始编辑,即原有内容会被删除。如果该文件不存在,则创建新文件。
w+ 打开一个文件用于读写。如果该文件已存在则打开文件,并从头开始编辑,即原有内容会被删除。如果该文件不存在,则创建新文件。
a 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存创建新文件进行写入。

file对象使用open函数来创建

模式 描述
file.close() 关闭文件。关闭后文件不能再进行读写操作。
file.read([size]) 从文件读取指定的字节数,如果未给定或为负则读取所有。
file.readline([size]) 读取整行,包括”\n”字符。
file.readlines([sizeint]) 读取所有行并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行,实际读取值可能比 sizeint 较大,因为需要填充缓冲区。
file.write(str) 将字符串写入文件,返回的是写入的字符长度。
file.writelines(sequence) 向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符。

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# #文件的读取
# hello = open(file="hello.txt",mode="r",encoding='utf-8') #r表示只读
# #编码
# content= hello.readlines()
# for i in content:
# print(i)
# hello.close() #类 成员函数

with open(file="hello.txt",mode="r",encoding='utf-8') as hello:
# 编码
content = hello.readlines()
for i in content:
print(i)

#文件写入
with open(file="hello.txt",mode="a",encoding='utf-8') as hello: #a是追加
# 编码
content = hello.write("大家好!\n")

九、模块安装与导入

通过pip来安装库

  1. pip是Python包管理工具,该工具提供了对Python包的查找、下载、安装、卸载的功能。
1
2
3
4
5
6
7
pip -- version

pip install some-package-name

pip uninstall some-package-name

pip list

导入库

1
2
3
4
5
6
7
8
9
import numpy as np
a = 1
b = 2
print(np.add(a + b))

#from numpy import add
#a = 1
#b = 2
#print(add(a + b))

十、数据分析

提出问题→准备数据→分析数据→获得结论→成果可视化

数据分析:把大量的数据进行统计和整理,得出结论,为后续的决策提供数据支持

matplotlib

  1. 能将数据进行可视化、更直观的呈现
  2. 使数据更加客观、更具说服力

matplotlib:最流行的Python底层绘图库,主要做数据可视化图表,名字取材于MATLAB,模仿MATLAB构建

常用的统计图:

折线图:以折线的上升或下降来表示统计数量的增减变化的统计图特点:能够显示数据的变化趋势,反映事物的变化情况。(变化)

直方图:由一系列高度不等的纵向条纹或线段表示数据分布的情况。一般用横轴表示数据范围,纵轴表示分布情况。特点:绘制连续性的数据,展示一组或者多组数据的分布状况(统计)

条形图:排列在工作表的列或行中的数据可以绘制到条形图中。特点:绘制连离散的数据,能够一眼看出各个数据的大小,比较数据之间的差别。(统计)

散点图:用两组数据构成多个坐标点,考察坐标点的分布,判断两变量之间是否存在某种关联或总结坐标点的分布模式。特点:判断变量之间是否存在数量关联趋势,展示离群点(分布规律)

折线图

axis轴:指的是x或者y这种坐标轴

示例代码1:

1
2
3
4
5
6
7
8
from matplotlib import pyplot as plt
x = range(2,26,2)
#数据在x轴的位置,是一个可迭代对象
y = [15,13,14.5,17,20,25,26,26,24,22,18,15]
#数据在y轴的位置,是一个可迭代对象
#(2,15),(4,13)……(24,15)
plt.plot(x,y) #传入x和y绘制折线图
plt.show() #执行程序展示图形

示例代码2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from matplotlib import pyplot as plt

x = range(2,26,2)
#数据在x轴的位置,是一个可迭代对象
y = [15,13,14.5,17,20,25,26,26,24,22,18,15]
#数据在y轴的位置,是一个可迭代对象
#(2,15),(4,13)……(24,15)

# 设置图片大小
fig = plt.figure(figsize = (20,8),dpi = 80) #在图像模糊时传入dpi能够使图片清晰

plt.plot(x,y) #传入x和y绘制折线图
# 保存图片
plt.savefig('./p1.png') #保存到当前文件下 也可以保存为svg矢量图格式,放大后不会有锯齿
plt.show() #执行程序展示图形

调整x或者y轴上的刻度,示例代码3:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from matplotlib import pyplot as plt

x = range(2,26,2)
#数据在x轴的位置,是一个可迭代对象
y = [15,13,14.5,17,20,25,26,26,24,22,18,15]
#数据在y轴的位置,是一个可迭代对象
#(2,15),(4,13)……(24,15)

# 设置图片大小
fig = plt.figure(figsize = (20,8),dpi = 80) #在图像模糊时传入dpi能够使图片清晰

# 设置x的刻度
_xtick_labels = [i/2 for i in range(4,49)]
# plt.xticks(x)
# plt.xticks(range(2,25,3))
# plt.xticks(_xtick_labels)
plt.xticks(_xtick_labels[::3]) #当刻度太密集时使用列表的步长(间隔取值),matplotlib会自动帮我们对应

# 设置y的刻度
plt.yticks(range(min(y),max(y)+1))

plt.plot(x,y) #传入x和y绘制折线图



# 保存图片
# plt.savefig('./p1.png') #保存到当前文件下 也可以保存为svg矢量图格式,放大后不会有锯齿
plt.show() #执行程序展示图形

设置中文显示:可以通过matplotlib.rc进行修改,具体方法可以参见源码(CTRL + 鼠标左键),以及加上坐标轴的描述和图的描述信息,示例代码4:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import random
from matplotlib import pyplot as plt
import matplotlib
# windows设置字体显示中文
matplotlib.rc("font",family="Microsoft Yahei",weight="bold")


x = range(0,120)
y = [random.randint(20,35) for i in range(120)]

plt.figure(figsize=(20,8),dpi = 80) #设置图片大小
plt.plot(x,y)

# 设置x轴的刻度

_xtick_labels = ["10点{}分".format(i) for i in range(60)]
_xtick_labels += ["11点{}分".format(i) for i in range(60)]

# 取步长,数字和字符串一一对应,数据的长度一样

plt.xticks(list(x)[::3],_xtick_labels[::3],rotation=45) #rotation旋转的度数

# 添加描述信息
plt.xlabel("时间")
plt.ylabel("温度 单位(℃)")
plt.title("10点到12点每分钟的气温变化情况")

plt.show()

图形中加上网格以及另一种方式设置中文字体,示例代码5:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from matplotlib import pyplot as plt
from matplotlib import font_manager

my_font = font_manager.FontProperties(fname = "C:\Windows\Fonts\simsun.ttc") # 设置宋体
y = [1,0,1,1,2,4,3,2,3,4,4,5,6,5,4,3,3,1,1,1]
x = range(11,31)

# 设置图形大小
plt.figure(figsize=(20,8),dpi=80)

plt.plot(x,y)

# 设置x轴刻度
_xtick_labels = ["{}岁".format(i) for i in x]
plt.xticks(x,_xtick_labels,fontproperties=my_font)

# 设置y轴刻度
plt.yticks(range(0,9))

# 绘制网格
plt.grid(alpha=0.4)

# 展示
plt.show()
python设置中文字体的三种方法

方法一

  • windows和linux设置字体的方法
1
2
3
4
5
import matplotlib
font = {'family' : 'Microsoft YaHei',
'weight' : 'bold',
'size' : 'larger'}
matplotlib.rc("font",**font)

方法二

  • windows和linux设置字体的方法
1
2
import matplotlib
matplotlib.rc("font",family='Microsoft YaHei',weight="bold")

方法三

  • 宋体和Times New Roman
1
2
3
4
5
6
7
from matplotlib import font_manager
# window系统下的字体路径
# 宋体:fname="C:\Windows\Fonts\simsun.ttc"
# Times New Roman:fname="C:\Windows\Fonts\times.ttf
my_font=font_manager.FontProperties(fname="C:\Windows\Fonts\simsun.ttc")
# 在需要中文显示的地方添加fontproperties=my_font即可
plt.xticks(list(x)[::3],_xtick_lables[::3],rotation=45,fontproperties=my_font)

在图形中绘制多条折线,以及设置线条的样式和添加图例等,示例代码6:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from matplotlib import pyplot as plt
from matplotlib import font_manager

my_font = font_manager.FontProperties(fname = "C:\Windows\Fonts\simsun.ttc") # 设置宋体
y_1 = [1,0,1,1,2,4,3,2,3,4,4,5,6,5,4,3,3,1,1,1]
y_2 = [1,0,3,1,2,2,3,3,2,1,2,1,1,1,1,1,1,1,1,1]
x = range(11,31)

# 设置图形大小
plt.figure(figsize=(20,8),dpi=80)

plt.plot(x,y_1,label="自己",color="orange",linestyle=":",linewidth=2) # 颜色 线条样式,线条粗细
plt.plot(x,y_2,label="同桌",color="cyan",linestyle="-.",linewidth=2)

# 设置x轴刻度
_xtick_labels = ["{}岁".format(i) for i in x]
plt.xticks(x,_xtick_labels,fontproperties=my_font)

# 设置y轴刻度
plt.yticks(range(0,9))

# 绘制网格
plt.grid(alpha=0.4)

# 添加图例
plt.legend(prop=my_font, loc='upper left') #字体 位置

# 展示
plt.show()

总结
  • 导入库
1
from matplotlib import pyplot plt
  • 设置图片大小
1
plt.figure(figsize=(20,80),dpi=80)
  • 绘图
1
plt.plot(x,y)	# x是所有坐标的x值,y是所有坐标的y值
  • 调整x或y轴的刻度
1
2
3
4
plt.xticks()
plt.yticks()
# 调整间距,则传一个参数(包含数字的可迭代对象),步长合适即可
# 添加字符串到x(y)轴 传入两个参数,分别是两个可迭代对象,数字和字符串最终会一一对应,只显示字符串
  • 展示
1
plt.show()
  • 保存
1
plt.savefig("file_path")
  • 图形的样式

color、linestyle、linewidth、alpha(透明度,从0-1)

  • 添加图形的描述
1
2
3
plt.xlabel()
plt.ylabel()
plt.title()
  • 网格
1
plt.gird(alpha=0.4,linestyle=)

散点图

技术要点:plt.scatter(x,y)

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from matplotlib import pyplot as plt
from matplotlib import font_manager

my_font = font_manager.FontProperties(fname="C:\Windows\Fonts\simsun.ttc")
y_3 = [11,17,16,11,12,11,12,6,6,7,8,9,12,15,14,17,18,21,16,17,20,14,15,15,15,19,21,22,22,22,23]
y_10 = [26,26,28,19,21,17,16,19,18,20,20,19,22,23,17,20,21,20,22,15,11,15,5,13,17,10,11,13,12,13,6]

x_3 = range(1,32)
x_10 = range(51,82)

# 设置图形大小
plt.figure(figsize=(20,8),dpi=80)

# 使用scatter绘制散点图,和之前绘制折线图的唯一区别
plt.scatter(x_3,y_3,label="3月份")
plt.scatter(x_10,y_10,label="10月份")

# 调整x轴的刻度

_x = list(x_3)+list(x_10)
_xtick_labels = ["3月{}日".format(i) for i in x_3]
_xtick_labels += ["10月{}日".format(i-50) for i in x_10]
plt.xticks(_x[::3],_xtick_labels[::3],fontproperties=my_font,rotation=45)

# 添加图例
plt.legend(loc="best",prop=my_font)
# 添加描述信息

plt.xlabel("时间",fontproperties=my_font)
plt.ylabel("温度",fontproperties=my_font)
plt.title("标题",fontproperties=my_font)

plt.show()

条形图

横向条形图,示例代码1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from matplotlib import pyplot as plt
from matplotlib import font_manager

my_font = font_manager.FontProperties(fname = "C:\Windows\Fonts\simsun.ttc") # 设置宋体
x = ["满江红","流浪地球2","孤注一掷","消失的她","封神第一部","八角笼中","长安三万里","熊出没","坚如磐石","人生路不熟"]
y = [45.44,40.29,38.48,35.23,26.33,22.07,18.24,14.95,13.43,11.84]


# 设置图片大小
plt.figure(figsize=(20,8),dpi=80)
# 绘制条形图
plt.bar(range(len(x)),y,width=0.3)
# 设置字符串到x轴
plt.xticks(range(len(x)),x,fontproperties=my_font,rotation=45)

plt.xlabel("影片名",fontproperties=my_font)
plt.ylabel("票房",fontproperties=my_font)
plt.title("”2023年度前十票房电影",fontproperties=my_font)

# 绘制表格
plt.grid()
# 保存图片
# plt.savefig("./p2.png")
# 展示
plt.show()

纵向条形图,示例代码2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from matplotlib import pyplot as plt
from matplotlib import font_manager

# 绘制横向条形图
my_font = font_manager.FontProperties(fname = "C:\Windows\Fonts\simsun.ttc") # 设置宋体
x = ["满江红","流浪地球2","孤注一掷","消失的她","封神第一部","八角笼中","长安三万里","熊出没","坚如磐石","人生路不熟"]
y = [45.44,40.29,38.48,35.23,26.33,22.07,18.24,14.95,13.43,11.84]


# 设置图片大小
plt.figure(figsize=(20,8),dpi=80)
# 绘制条形图
plt.barh(range(len(x)),y,height=0.3,color = 'orange')
# 设置字符串到y轴
plt.yticks(range(len(x)),x,fontproperties=my_font)
# 添加网格
plt.grid(alpha=0.3)

# 保存图片
# plt.savefig("./p2.png")
# 展示
plt.show()

绘制多个条形图,示例代码3:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from matplotlib import pyplot as plt
from matplotlib import font_manager

my_font = font_manager.FontProperties(fname = "C:\Windows\Fonts\simsun.ttc") # 设置宋体

a = ["猩球崛起3:终极大战","多克尔克","蜘蛛侠:英雄归来","战狼2"]
b_16 = [15746,312,4497,319]
b_15 = [12357,156,2045,168]
b_14 = [2358,399,2358,362]

bar_width = 0.2
x_14 = list(range(len(a)))
x_15 = [i + bar_width for i in x_14]
x_16 = [i + bar_width*2 for i in x_14]
# 设置图片大小
plt.figure(figsize=(20,8),dpi=80)
# 绘制条形图
plt.bar(x_14,b_14,width=bar_width,label="9月14日")
plt.bar(x_15,b_15,width=bar_width,label="9月15日")
plt.bar(x_16,b_16,width=bar_width,label="9月16日")

# 设置图例
plt.legend(prop=my_font)
# 设置x轴的刻度
plt.xticks(x_15,a,fontproperties=my_font)
# 绘制表格
plt.grid()
# 保存图片
# plt.savefig("./p2.png")
# 展示
plt.show()

条形图的更多应用场景

  • 数量统计
  • 频率统计(市场饱和度)

直方图

组数:将数据进行分组,当数据在100个以内时,按数据多少常分5-12组
$$
组数=\frac{极差}{组距}=\frac{max{(a )-min(a)}}{binwidth}
$$
组距:指每个小组的两个端点的距离

示例代码1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import random

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import font_manager


a=[102,103,113,116,117,126,134,95,138,117,111,78,132,124,113,150,110,117,86,95,144,105,126,110.128,128,115.99,136,
130,126,130,123,106,112,138,123,86,101,99,136,123,117,119,105,137,123,128,125.104,109,134,126,116,125,
127,105,129, 116,108,132,103,136,118,102,120,114.105,115,132,145,119,121,112,139,125,138,109,120,107,
132,134,156,106,117,127,139,139,119,140,83,110,102,123,107,143,115,136,118,139,123,112,118,125,109,119,
133.112,114.122,109,106,123,116,131,127,115, 118,112,135,115,146,137,116,103.144,83,123,111,110, 111,
100, 154,136, 100, 118, 119,133,134,106, 129,126,110,111, 109, 141,120,117,106,149,122,122, 110, 118,
127, 121, 114,125,126,114, 140,103,130,141,117,106,114,121,114,133,137,92,121,112,146,97,137,105,98,
117,112,81,97,139, 123,134, 106, 144, 110, 137,137, 111, 104, 117, 100, 111,101, 110,105,129,137, 112,
120, 113,133,112,83, 94, 146,133,101,131,116,111,84,137,115,122,106,144,109,123,116,111,111,133,150]

# 计算组数
d = 3 # 组距
num_bins = (max(a) - min(a)) // d # 组数

# 设置图形大小
plt.figure(figsize=(20,8),dpi=80)

# 绘制条形图
plt.hist(a,num_bins)

# 设置x轴刻度
plt.xticks(range(min(a),max(a),d))

plt.grid()
plt.show()

查看频率分布直方图:plt.hist(a,num_bins,density=True)

示例代码2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import random

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import font_manager


a=[102,103,113,116,117,126,134,95,138,117,111,78,132,124,113,150,110,117,86,95,144,105,126,110.128,128,115.99,136,
130,126,130,123,106,112,138,123,86,101,99,136,123,117,119,105,137,123,128,125.104,109,134,126,116,125,
127,105,129, 116,108,132,103,136,118,102,120,114.105,115,132,145,119,121,112,139,125,138,109,120,107,
132,134,156,106,117,127,139,139,119,140,83,110,102,123,107,143,115,136,118,139,123,112,118,125,109,119,
133.112,114.122,109,106,123,116,131,127,115, 118,112,135,115,146,137,116,103.144,83,123,111,110, 111,
100, 154,136, 100, 118, 119,133,134,106, 129,126,110,111, 109, 141,120,117,106,149,122,122, 110, 118,
127, 121, 114,125,126,114, 140,103,130,141,117,106,114,121,114,133,137,92,121,112,146,97,137,105,98,
117,112,81,97,139, 123,134, 106, 144, 110, 137,137, 111, 104, 117, 100, 111,101, 110,105,129,137, 112,
120, 113,133,112,83, 94, 146,133,101,131,116,111,84,137,115,122,106,144,109,123,116,111,111,133,150]

# 计算组数
d = 3 # 组距
num_bins = (max(a) - min(a)) // d # 组数

# 设置图形大小
plt.figure(figsize=(20,8),dpi=80)

# 绘制条形图
plt.hist(a,num_bins,density=True)


# 设置x轴刻度
plt.xticks(range(min(a),max(a),d))

plt.grid()
plt.show()

示例代码3:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import random

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import font_manager

interval = [0,5,10,15,20,25,30,35,40,45,60,90]
width = [5,5,5,5,5,5,5,5,5,15,30,60]
quantity = [836,2765,3465,4356,5432,3546,6476,6543,5352,2435,3452,1243]

# 设置图形大小
plt.figure(figsize=(20,8),dpi=80)
plt.bar(range(len(quantity)),quantity,width=1)

# 设置x轴的刻度
_x = [i-0.5 for i in range(13)]
_xtick_labels = interval + [150]
plt.xticks(_x,_xtick_labels)

plt.grid()
plt.show()

直方图更多的使用场景

  • 用户的年龄分布状态
  • 一段时间内用户点击次数的分布状态
  • 用户活跃时间的分布状态

更多的绘图工具

  • plotly:可视化工具中的github,相比于matplotlib更加简单,图形更加漂亮,同时兼容matplotlib和pandas,使用方法照着文档写即可

文档地址

numpy

numpy:一个在Python中做科学计算的基础库,重在数值计算,也是大部分PYTHON科学计算库的基础库,多用于在大型、多维数组上执行数值运算

numpy创建数组(矩阵),以及numpy中数据的类型

示例代码1如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import random

import numpy
import numpy as np
from serial.tools.miniterm import Out

# 使用numpy生成数组,得到ndarray数据类型
a = np.array([1,2,3,4,5])
b = np.array(range(1,6))
c = np.arange(1,6)
print(a)
print(type(a))
print(b)
print(type(b))
print(c)
print(type(c))
print(c.dtype) # 数据类型
print("="*50)
# numpy中的数据类型
# d = np.array(range(1,4),dtype=float)
d = np.array(range(1,4),dtype="i1")
print(d)
print(d.dtype)

print("="*50)
# numpy中的bool数据类型
e = np.array([1,0,1,1,0],dtype=bool)
print(e)
print(e.dtype)

# 调整数据类型
f = e.astype("int8")
print(f)
print(f.dtype)

print("="*50)
# numpy中的小数
g = np.array([random.random() for i in range(10)])
print(g)
print(g.dtype)

h = np.round(g,2) # 保留两位小数
print(h)
print(h.dtype)

数组的形状(一维、二维、三维),reshape()中的参数个数表示几维数组,示例代码2如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import numpy as np

t1 = np.arange(12) # 一维数组
print(t1)
print(t1.shape)

t2 = np.array([[1,2,3],[4,5,6]]) # 二维数组
print(t2)
print(t2.shape)

t3 = np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]]) # 三维数组 立体矩阵
print(t3)
print(t3.shape)

# 修改数组形状
t4 = np.arange(12)
print(t4)
print(t4.shape)
t4 = t4.reshape((3,4)) # 参数(3,4)表示传的是一个元组 reshape函数是将结果作为返回值返回,不改变原数组
print(t4)
print(t4.shape)

t5 = np.arange(24).reshape((2,3,4)) # 块数 行数 列数
print(t5)
print(t5.shape)

数组的计算(数组与数之间的运算,数组与数组之间的运算)

  • 数组与数之间的运算满足numpy广播机制,即进行运算时,加减乘除的值被广播到所有的元素上
  • 数组与数组进行运算时,如果维度不匹配则会报错,但是有些情况下是可以进行运算的

广播原则:如果两个数组的后缀维度(trailing dimension,即从末尾开始算起的维度)的轴长度相符或其中一方的长度为1,则认为他们是广播兼容的。广播会在缺失和(或)长度为1的维度上进行。

示例代码3:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import numpy as np
t5 = np.arange(24).reshape((4,6))
# 数组和数进行计算 数组中的每个元素都与数进行操作
# t5 = t5 + 2
# t5 = t5 * 2
# t5 = t5 / 2
# t5 = t5 / 0
print(t5)
print(t5.shape)
t6 = np.arange(100,124).reshape((4,6))
print(t6)
print("="*50)
t6 = t6 + t5 # 对应位进行计算
print(t6)
print("="*50)
t7 = np.arange(6).reshape((1,6))
print(t7)
print("="*50)
print(t7 + t6)

numpy中可以理解为方向,使用数字0、1、2……表示,对于一个一维数组,只有一个0轴,对于二维数组(shape(2,2)),有0轴和1轴,对于三维数组(shape(2,2,3)),有0,1,2轴。

numpy读取数据

CSV:Comma-Separated Value,逗号分隔值文件

显示:表格状态

源文件:换行和逗号分隔行列的格式化文本,每一行的数据表示一条记录

由于CSV便于展示,读取和写入,所以很多地方采用CSV的格式存储和传输中小型的数据。

1
np.loadtxt(frame,dtype=np.float,delimiter=None,skiprows=0,usecols=None,unpack=False)

转置的三种方法

  1. t1.transpose() 转置
  2. t1.T 转置
  3. t1.swapaxes() 交换轴
参数 解释
frame 文件、字符串或产生器,可以是.gz或bz2压缩文件
dtype 数据类型,可选,CSV的字符串以什么数据类型读入数组中,默认np.float
delimiter 分隔字符串,默认是任何空格,改为 逗号
skiprows 跳过前x行,一般跳过开头第一行表头
usecols 读取指定的列,索引,元组类型
unpack 如果为True,读入属性将分别写入不同数组变量(即会实现矩阵转置效果),False读入数据只写入一个数组变量,默认为False
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import numpy as np

test_path = "./test.csv"
t1 = np.loadtxt(test_path, delimiter=',',dtype=int)
t2 = np.loadtxt(test_path, delimiter=',',dtype=int,unpack=True) # unpack=True实现矩阵转置效果
print(t1)
print("="*50)
print(t2)
print("="*50)
t3 = np.arange(24).reshape((4,6))
print(t3)
print("="*50)
# t4 = np.transpose(t3) # 转置
# t4 = t3.T # 转置
t4 = t3.swapaxes(0,1) # 交换轴(转置)
print(t4)
numpy索引和切片以及数值修改

具体操作和python列表中的操作一样,索引以及切片示例代码1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import numpy as np

test_path = "./test.csv"
t1 = np.loadtxt(test_path, delimiter=',',dtype=int,unpack=True)
print(t1)
print("="*50)

# 取行
print(t1[1]) # 表示取第一行数据,索引是从0开始
print("="*50)
# 取连续多行
print(t1[2:]) # 表示取第二行以及第二行之后的数据
print("="*50)
# 取不连续多行
print(t1[[1,3,4]]) # 相当于传入了一个元组
print("="*50)
# 取列
print(t1[1,:]) # 表示取1行所有列元素
print("="*50)
print(t1[:,1]) # 表示取每一行的第1列
print("="*50)
print(t1[[2,0,3],1]) # 表示取2,0,3行中的第一列
print("="*50)
# 取连续的多列
print(t1[:,0:])
print("="*50)
# 取不连续的多列
print(t1[3,[0,1]])
print("="*50)
print(t1[2:4,[0,1]]) # 取第二行到第四行(不包括第四行,左闭右开)中第0和第1列的数据
print("="*50)
# 取多个不相邻的点
print(t1[[0,2,3],[1,0,1]]) # 选取的是(0,1),(2,0),(3,1)的点
print("="*50)

numpy布尔索引和数值修改,示例代码2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import numpy as np

test_path = "./test.csv"
t1 = np.loadtxt(test_path, delimiter=',',dtype=int,unpack=True)
print(t1)
print("="*50)
print(t1<10) # 布尔索引
print("="*50)
t1[t1<10] = 3 # 数值修改
t1[t1>20] = 50 # 数值修改
# numpy中的clip(裁剪)
print(t1.clip(10,18)) # 把小于10的赋值为10,把大于18的赋值为18
print("="*50)
# numpy中的三元运算符
# t1 = np.where(t1<10,0,10) # t1中小于10的元素赋值为0,大于10的元素赋值为10
print(t1)

numpy中的nan和常用方法

  • 数组的拼接
  • 数组的行列交换

示例代码1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import numpy as np

t1 = np.arange(0,12).reshape(2,6).astype(float)
print(t1)
print("*"*50)
t2 = np.arange(13,25).reshape(2,6).astype(float)
print(t2)
print("*"*50)

# 数组的拼接
print(np.vstack((t1,t2))) # 竖直拼接
print("*"*50)
print(np.hstack((t1,t2))) # 横向拼接

# 数组的行列交换

print("*"*50)
t1[[0,1],:] = t1[[1,0],:] # 交换第0行和第1行的所有元素
print(t1)
print("*"*50)
t2[:,[0,2]] = t2[:,[2,0]] # 交换第0列和第2列的所有元素
print(t2)
print("*"*50)

示例代码2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import numpy as np

data1_path = "./test.csv"
data2_path = "./test2.csv"

# 加载数据
data1 = np.loadtxt(data1_path, delimiter=',',dtype=int)
data2 = np.loadtxt(data2_path, delimiter=',',dtype=int)

# 添加信息
# 构造全为0的数据
zeros_data = np.zeros((data1.shape[0],1)).astype(int)
# 构造全为1的数据
ones_data = np.ones((1,data2.shape[1])).astype(int)

# 横向拼接
t1 = np.hstack((zeros_data,data1))
tt1 = np.vstack((ones_data,data1))
t2 = np.hstack((zeros_data,data2))
tt2 = np.vstack((ones_data,data2))
print(t1)
print("*"*50)
print(t2)
print("*"*50)
print(tt1)
print("*"*50)
print(tt2)
print("*"*50)

更多的一些常用方法:

  • 获取最最大值和最小值的位置
1
2
np.argmax(t,axis=0)
np.argmin(t,axis=1)
  • 创建一个全0的数组
1
np.zeros((3,4))
  • 创建一个全1的数组
1
np.ones((2,3))
  • 创建一个对角线全为1的正方形数组(矩阵)
1
np.eye(4)

numpy生成随机数

参数 解释
.rand(d0,d1,……dn) 创建d0-dn维度的均匀分布的随机数组,浮点数,范围是0-1
.randn(d0,d1,……,dn) 创建d0-dn维度的标准正态分布的随机数组,浮点数,平均数为0,标准差为1
.randint(low,high,(shape)) 从给定的上下限范围选取随机数整数,范围是[low,high),形状是shape
.uniform(low,high,(size)) 产生具有均匀分布的数组,low起始值,high结束值,size是形状
.normal(loc,scale,(size)) 从指定正态分布中随机抽取样本,分布中心是loc(概率分布的均值),标准差是scale,形状是size
.seed(s) 随机数种子,s是给定的种子值,因为计算机生成的是伪随机数,所以通过设定相同的随机数种子,可以每次生成相同的随机数

示例代码:

1
2
3
4
import numpy as np

t1 = np.random.randint(2,10,(2,5))
print(t1)

==numpy的注意点copy和view==

  1. a=b 完全不复制,a和b相互影响
  2. a=b[:] 视图的操作,一种切片,会创建新的对象a,但是a的数据完全由b保管,他们两个的数据变化是一致的
  3. a=b.copy() 复制,a和b相互不影响

numpy中的nan和inf

nan:not a number 表示不是一个数字

当我们读取本地的文件为float时,如果有缺失,就会出现nan;当做了一个不合适的计算的时候(比如无穷大(inf)减去无穷大)

inf(-inf,inf):inf表示正无穷,-inf表示负无穷

当一个数字除以0,(python中直接会报错,numpy中是一个inf或者-inf)

nan和任何值计算结果都为nan

isnan()用来检测是否为nan值

示例代码1:

1
2
3
4
5
6
7
8
import numpy as np
t1 = np.nan
t2 = np.nan
print(t1 == t2)
print(type(t1))
print(t1 != t2)
t3 = np.inf
print(type(t3))

numpy中常用函数统计

求和:t.sum(axis=None)

均值:t.mean(a,axis=None) 受离群点的影响较大

中值:np.median(t,axis=None)

最大值:t.max(axis=None)

最小值:t.min(axis=None)

极值:np.ptp(t,axis=None) 即最大值和最小值的差值

标准差:t.std(axis=None)

==默认返回多维数组的全部的统计结果,如果指定axis则返回一个当前轴上的结果==

示例代码2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import numpy as np
t3 = np.arange(0,12).reshape(3,4)
print(t3)
print("*"*50)
t4 = np.arange(0,12).reshape(3,4)
print(t4)
print("*"*50)
print(np.sum(t3,axis=0)) # 求和
print("*"*50)
print(np.sum(t3,axis=1)) # 求和
print("*"*50)
print(t3.mean(axis=0)) # 均值
print("*"*50)
print(t3.max(axis=0)) # 最大值
print("*"*50)
print(t3.min(axis=0)) # 最小值
print("*"*50)
print(t3.ptp(axis=0)) # 极值
print("*"*50)
print(t3.std()) # b标准差

示例代码3:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import numpy as np
def fill_array(t1):
for i in range(t1.shape[1]):
temp_col = t1[:,i] # 当前的一列
nan_num = np.count_nonzero(temp_col != temp_col)
if nan_num != 0: # 不为0说明当前这列有nan
temp_not_nan_col = temp_col[temp_col == temp_col] # 当前这一列不为nan的array
# 选中当前为nan的位置,把值赋值为不为nan的均值
temp_col[np.isnan(temp_col)] = temp_not_nan_col.mean()
return t1

if __name__ == '__main__':
t1 = np.arange(0, 12).reshape(3, 4).astype(float)
t1[1, :2] = np.nan
print(t1)
print("*"*50)
t1 = fill_array(t1)
print(t1)
上一篇:
Maven
下一篇:
Javaweb