前言:python数据挖掘的基础知识,参考网上很多文章和博客进行总结,主要是为了方便自己写代码的时候查看,发现有用的方法,随时补充
数据挖掘专栏
函数式语言与面向对象语言的结合,Python语⾔的⼀个重要特性就是它的对象模型的⼀致性。 每个数字、 字符串、 数据结构、 函数、 类、模块等等, 都是在Python解释器的自有“盒⼦”内, 它被认为是Python对象。 每个对象都有类型(例如, 字符串或函数) 和内部数据。 在实际中, 这可以让语⾔⾮常灵活, 因为函数也可以被当做对象使用,提高开发效率。在编程中可以多多使用对象的思想(多class类和def函数)
Python语言目前主要的应用领域包括Web开发、大数据开发(数据分析)、人工智能开发(机器学习、自然语言处理、计算机视觉等)、嵌入式开发和各种后端服务开发(App后端以及各种小型应用的后端服务开发),由于Python语言具备强大的语言整合能力,所以能够完成更多场景的应用。
Python支持对整数和浮点数直接进行四则混合运算,运算规则和数学上的四则运算规则完全一致。
In[2]: 7
Out[2]: 7
In[3]: 7*4
Out[3]: 28
In[4]: 7**2
Out[4]: 49
In[5]: 7/2
Out[5]: 3.5
In[6]: 7//2
Out[6]: 3
In[7]: 7%2
Out[7]: 1
In[8]: 7.202
Out[8]: 7.202
In[9]: 7.202/2
Out[9]: 3.601
In[10]: 7.202//2
Out[10]: 3.0
import math # 更多运算
help(math)
[注]:
在Python中用引号引起来的字符集称之为字符串,比如:‘hello’、“my Python”、"2+3"等都是字符串 Python中字符串中使用的引号可以是单引号、双引号跟三引号。
In[15]: 'hello'
Out[15]: 'hello'
In[16]: "hello 'my girl'"
Out[16]: "hello 'my girl'"
转义字符\可以转义很多字符,比如\n表示换行,\t表示制表符等等
In[25]: print("hello world!\nhello Python!")
hello world!
hello Python!
In[26]: 'It\'s a dog!'
Out[26]: "It's a dog!"
In[44]: str1 = "I Love Python"
In[45]: str1.lower()
Out[45]: 'i love python'
In[46]: str1.upper()
Out[46]: 'I LOVE PYTHON'
In[47]: str1.center(20,'*')
Out[47]: '***I Love Python****'
In[48]: str1.ljust(20,'*')
Out[48]: 'I Love Python*******'
In[49]: str1.rjust(20,'*')
Out[49]: '*******I Love Python'
In[51]: str1.count('o',0,10)
Out[51]: 1
In[52]: str1.find("o",4,12)
Out[52]: 11
In[53]: str1.rfind("o",4,12)
Out[53]: 11
In[55]: "{}不爱{}".format("我","你")
Out[55]: '我不爱你'
In[56]: "{people_1}不爱{people_2}".format(people_1="我",people_2="你")
Out[56]: '我不爱你'
In[57]: "{1}不爱{0}".format("我","你")
Out[57]: '你不爱我'
In[58]: "输出整数的二进制形式: {:b}".format(123456)
Out[58]: '输出整数的二进制形式: 11110001001000000'
In[59]: student = {"name":["张三","李四"],"idcard":[1,2]}
In[60]: "我的名字是{name[0]},我的学号是{idcard[0]}".format_map(student)
Out[60]: '我的名字是张三,我的学号是1'
In[61]: str1.endswith('thon')
Out[61]: True
In[62]: str1.startswith('i')
Out[62]: False
In[63]: str1.isalnum()
Out[63]: False
In[64]: str1.isalpha()
Out[64]: False
In[65]: str1.isdigit()
Out[65]: False
In[66]: str1.islower()
Out[66]: False
In[67]: str1.isupper()
Out[67]: False
14、 strip()、lstrip()、rstrip():从字符串str中去掉在其左右(左)(右)两边chars中列出的字符。(常用来去空格)
In[68]: str1.strip('thon')
Out[68]: 'I Love Py'
In[69]: str1.lstrip('thon')
Out[69]: 'I Love Python'
In[70]: str1.rstrip('thon')
Out[70]: 'I Love Py'
In[71]: str = "https://www.baidu.com/"
In[72]: str.partition("://")
Out[72]: ('https', '://', 'www.baidu.com/')
In[73]: str.split(':')
Out[73]: ['https', '//www.baidu.com/']
In[75]: ','.join(str)
Out[75]: 'p,y,t,h,o,n'
In[76]: L = ["1","2","3"]
In[77]: ','.join(L)
Out[77]: '1,2,3'
In[80]: str.replace('o','*')
Out[80]: 'pyth*n'
In[92]: str = '12345'
In[93]: str_1 = '12345'
In[94]: str + str_1
Out[94]: '1234512345'
In[96]: '1' in str
Out[96]: True
符号 | 含义 |
---|---|
. | 匹配任意字符串,除了\n |
| | 转义符,保留字符串中的特殊元字符 |
[ ] | 字符组 |
\d | 匹配任意数字 |
\s | 匹配空白字符 |
\w | 匹配字母和下划线 |
* | 匹配前一个字符组0到无穷 |
+ | 匹配前一个字符组1到无穷 |
? | 匹配前一个字符组0到1 |
(.*?) | 匹配任意字符串 |
In[110]: str = '1 2 3'
In[111]: pattern = re.compile(r'[ ]+')
In[112]: pattern.split(str)
Out[112]: ['1', '2', '3']
In[105]: str = 'abcdefghabcdef'
In[106]: pattern = re.compile(r'(ab)(cd)ef(gh)')
In[107]: pattern.findall(str)
Out[107]: [('ab', 'cd', 'gh')]
In[108]: pattern = re.compile(r'(ab)(cd)ef')
In[109]: pattern.findall(str)
Out[109]: [('ab', 'cd'), ('ab', 'cd')]
布尔类型还可以与其他数据类型做 and、or和not运算
In[41]: type(False)
Out[41]: bool
In[42]: a = 1
In[43]: True and a == 2
Out[43]: False
这里简单了解一下就行,可以以后在pandas中重点学习
In[42]: import time
...:localtime = time.localtime(time.time())
In[43]: time.time()
Out[43]: 1584359192.1000078
In[44]: localtime
Out[44]: time.struct_time(tm_year=2020, tm_mon=3, tm_mday=16, tm_hour=19, tm_min=46, tm_sec=23, tm_wday=0, tm_yday=76, tm_isdst=0)
In[45]: localtime = time.asctime( time.localtime(time.time()) )
In[46]: localtime
Out[46]: 'Mon Mar 16 19:48:59 2020'
In[48]: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
Out[48]: '2020-03-16 19:52:00'
In[49]: time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())
Out[49]: 'Mon Mar 16 19:52:12 2020'
In[51]: a = "Sat Mar 28 22:24:24 2016"
In[52]: time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))
Out[52]: 1459175064.0
列表(list)、元组(tuple)、字典(dict),非常重要!!!
用来存储一连串元素的容器,列表用[]来表示,其中元素的类型可不相同。
In[2]: L=[1,2,3]
In[3]: L
Out[3]: [1, 2, 3]
In[4]: L[0]
Out[4]: 1 # 从0开始索引
In[5]: L[0:2] # 切片索引时,包括左端点,不包括右端点
Out[5]: [1, 2]
【注】:函数属于整个文件, 方法属于某一个类, 方法如果离开类就不行,其实我们在用的时候区别不大,了解一下就可以(纯属个人感受)
In[9]: L=[1,2,3]
In[10]: len(L)
Out[10]: 3
In[11]: min(L)
Out[11]: 1
In[12]: max(L)
Out[12]: 3
In[88]: L = [1, 2]
In[89]: L_1 = [2, 3]
In[90]: L+L_1
Out[90]: [1, 2, 2, 3]
In[91]: 1 in L
Out[91]: True
In[19]: L=[1,2,3]
In[20]: L.append(1)
In[21]: L
Out[21]: [1, 2, 3, 1]
In[24]: L.insert(0,5)
In[25]: L
Out[25]: [5, 1, 2, 3, 1, 0]
In[25]: L
Out[25]: [5, 1, 2, 3, 1, 0]
In[26]: L.remove(1)
In[27]: L
Out[27]: [5, 2, 3, 1, 0]
# 删除所有匹配项
while 1 in L:
L.remove(1)
In[27]: L
Out[27]: [5, 2, 3, 1, 0]
In[28]: L.count(5)
Out[28]: 1
In[29]: L
Out[29]: [5, 2, 3, 1, 0]
In[30]: L.index(3)
Out[30]: 2
In[31]: L
Out[31]: [5, 2, 3, 1, 0]
In[32]: L.reverse()
In[33]: L
Out[33]: [0, 1, 3, 2, 5]
In[33]: L
Out[33]: [0, 1, 3, 2, 5]
In[34]: L.sort(reverse = True)
In[35]: L
Out[35]: [5, 3, 2, 1, 0]
In[35]: L
Out[35]: [5, 3, 2, 1, 0]
In[36]: L.pop(0)
Out[36]: 5
In[37]: L
...:
Out[37]: [3, 2, 1, 0]
元组类似列表,元组里面的元素也是进行索引计算。列表里面的元素的值可以修改,而元组里面的元素的值不能修改,只能读取。
tuple可以用list的函数,不能用list的方法
In[81]: tup = 4, 5, (6, 7)
In[82]: a, b, (c, d) = tup
In[83]: c
Out[83]: 6
In[84]: tup[0] # 从0开始索引
Out[84]: 4
In[85]: tup[0:2] # 包括左端点,不包括右端点
Out[85]: (4, 5)
元组中的元素值是不允许修改的,但我们可以对元组进行连接组合
In[86]: tup_2 = 1, 2
In[87]: tup_2 + tup
Out[87]: (1, 2, 4, 5, (6, 7))
In[97]: 1 in tup
Out[97]: False
In[98]: len(tup)
Out[98]: 3
In[102]: tup = 1,2,3
In[103]: min(tup)
Out[103]: 1
In[104]: max(tup)
Out[104]: 3
In[105]: del tup
In[106]: tup
NameError: name 'tup' is not defined
In[83]: list_1 = [1,2,3]
In[84]: list_2 = [1,2,3]
In[85]: L = zip(list_1,list_2)
In[86]: list(L)
Out[86]: [(1, 1), (2, 2), (3, 3)]
In[2]: dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
In[3]: dict
Out[3]: {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
In[4]: dict['Name']
Out[4]: 'Zara'
In[7]: dict.get('Name')
Out[7]: 'Zara'
In[9]: 'Name' in dict
Out[9]: True
In[10]: dict.items()
Out[10]: dict_items([('Name', 'Zara'), ('Age', 7), ('Class', 'First')])
In[11]: dict.keys()
Out[11]: dict_keys(['Name', 'Age', 'Class'])
In[12]: dict.values()
Out[12]: dict_values(['Zara', 7, 'First'])
In[13]: dict_1={'Name':'Tom'}
In[14]: dict.update(dict_1)
In[15]: dict
Out[15]: {'Name': 'Tom', 'Age': 7, 'Class': 'First'}
In[16]: dict_1.clear()
In[17]: dict_1
Out[17]: {}
In[32]: dict_1 = {'1':'a','2':'b'}
In[33]: dict = dict_1.copy()
In[34]: dict.pop('1')
Out[34]: 'a'
In[35]: dict_1
Out[35]: {'1': 'a', '2': 'b'}
In[36]: dict
Out[36]: {'2': 'b'}
In[37]: dict.clear()
In[38]: dict_1
Out[38]: {'1': 'a', '2': 'b'}
In[39]: dict_1.clear()
In[40]: dict
Out[40]: {}
In[60]: dict_3 = dict(dict_1,**dict_2)
In[61]: dict_3
Out[61]: {'1': 'a', '2': 'b', '3': 'c'}
In[62]: dict_3.pop('1')
Out[62]: 'a'
In[63]: dict_3
Out[63]: {'2': 'b', '3': 'c'}
In[64]: dict_4 = {k:v for k, v in dict_3.items() if v == 'c'}
In[65]: dict_4
Out[65]: {'3': 'c'}
In[19]: s = 'I love python'
In[20]: L = list(s.split(' '))
In[21]: L
Out[21]: ['I', 'love', 'python']
In[23]: ' '.join(L)
Out[23]: 'I love python'
In[24]: tup = (1,2,3)
In[25]: L = list(tup)
In[26]: L
Out[26]: [1, 2, 3]
In[27]: tuple(L)
Out[27]: (1, 2, 3)
In[34]: L1 = ['a','b','c']
In[35]: L2 = [2,3,4]
In[36]: dict(zip(L1,L2))
Out[36]: {'a': 2, 'b': 3, 'c': 4}
In[38]: list(dit)
Out[38]: ['name', 'age', 'gender', 'address']
In[39]: list(dit.values())
Out[39]: ['try', '20', 'male', 'anhui']
In[40]: list(dit.items())
Out[40]: [('name', 'try'), ('age', '20'), ('gender', 'male'), ('address', 'anhui')]
In[88]: if 'py' in 'python':
...: print('Yes')
...:elif 'java' in 'python':
...: print('can')
...:else: print('No')
...:
Yes
In[89]: for i in range(3):
...: print(i)
...:
0
1
2
函数是Python中最主要也是最重要的代码组织和复⽤⼿段。 作为最重要的原则, 如果你要重复使⽤相同或⾮常类似的代码, 就需要写⼀个函数。 通过给函数起⼀个名字, 还可以提⾼代码的可读性。函数使⽤ def 关键字声明, ⽤ return 关键字返回值:
In[90]: def my_function(x, y, z):
...: if z > 1:
...: return z * (x + y)
...: else:
...: return z / (x + y)
...:
In[91]: my_function(1,1,1.5)
Out[91]: 3.0
匿名函数lambda:是指一类无需定义标识符(函数名)的函数或子程序。
lambda 函数可以接收任意多个参数 (包括可选参数) 并且返回单个表达式的值。lambda函数所需的代码量远远少于普通函数,也就是说使用Lambda可以精简代码,加速Python程序运行,要学会多用。
In[92]: a = lambda x,y: x*y
In[93]: a(2,3)
Out[93]: 6
name == 'main’是Python的main函数入口。并非说,加入这句才能使用python xxx.py来执行,而是说,这里可以判断,当前是否是直接被python直接调用执行。
if __name__ == '__main__':
os模块提供了多数操作系统的功能接口函数。当os模块被导入后,它会自适应于不同的操作系统平台,根据不同的平台进行相应的操作,在python编程时,经常和文件、目录打交道,这时就离不了os模块。
In[113]: import os
In[114]: os.getcwd()
Out[114]: 'C:\\Users\\1\\WorkSpace\\python'
In[116]: os.chdir('CT data')
In[117]: os.getcwd()
Out[117]: 'C:\\Users\\1\\WorkSpace\\python\\CT data'
In[7]: os.listdir('data analyst')
Out[7]: ['pd_mysql.py', '__pycache__']
In[4]: os.removedirs('C:\\Users\\1\\WorkSpace\\python\\CT data')
In[6]: 'CT data' in os.listdir('C:\\Users\\1\\WorkSpace\\python')
Out[6]: False
In[12]: fd = os.open('data analyst/1.txt', os.O_RDWR|os.O_CREAT)
In[15]: os.write(fd, 'This is test'.encode())
Out[15]: 12
In[2]: import os
In[3]: os.rename('data analyst/1.txt', 'data analyst/2.txt')
In[4]: os.listdir('data analyst')
Out[4]: ['2.txt', 'pd_mysql.py', '__pycache__']