利用python进行数据分析(一)速成python
因为在学校里一直用C++,然后最近在做项目需要进行大量数据分析需要用到python,所以拿出几天时间来速成一下。
简单的基础知识已经正在菜鸟教程过了一遍了,根据书的第二章再整理一遍。
(待更)
一、数据结构和序列
1.1 元祖
特点:固定长度,元素不可改变。但若某个元素是list等,可以改变。
几个函数:
tuple 将任意序列或迭代器转换成元组
In [5]: tuple([4, 0, 2])
Out[5]: (4, 0, 2)
In [6]: tup = tuple('string')
In [7]: tup
Out[7]: ('s', 't', 'r', 'i', 'n', 'g')
合并元组直接用 +
元组乘以一个整数,像列表一样,会将几个元组的复制串联起来
元祖拆分
In [15]: tup = (4, 5, 6)
In [16]: a, b, c = tup
In [17]: b
Out[17]: 5
In [27]: seq = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
In [28]: for a, b, c in seq:
....: print('a={0}, b={1}, c={2}'.format(a, b, c))
a=1, b=2, c=3
a=4, b=5, c=6
a=7, b=8, c=9
关于format 函数

#交换变量值可以直接
In [24]: b, a = a, b
*元祖拆分 : rest用法
In [29]: values = 1, 2, 3, 4, 5
In [30]: a, b, *rest = values
In [31]: a, b
Out[31]: (1, 2)
In [32]: rest
Out[32]: [3, 4, 5]
count统计元素出现频率
In [34]: a = (1, 2, 2, 2, 3, 4, 2)
In [35]: a.count(2)
Out[35]: 4
1.2列表
特点:长度可变,内容可修改。
append : 在尾部添加元素
insert:在某位置添加元素
In [36]: a_list = [2, 3, 7, None]
In [37]: tup = ('foo', 'bar', 'baz')
In [38]: b_list = list(tup)
In [39]: b_list
Out[39]: ['foo', 'bar', 'baz']
In [40]: b_list[1] = 'peekaboo'
In [41]: b_list
Out[41]: ['foo', 'peekaboo', 'baz']
In [45]: b_list.append('dwarf')
In [46]: b_list
Out[46]: ['foo', 'peekaboo', 'baz', 'dwarf']
In [47]: b_list.insert(1, 'red')
In [48]: b_list
Out[48]: ['foo', 'red', 'peekaboo', 'baz', 'dwarf']
pop:根据位置删除
remove:根据元素内容删除(删除第一个)
In [48]: b_list
Out[48]: ['foo', 'red', 'peekaboo', 'baz', 'dwarf']
In [49]: b_list.pop(2)
Out[49]: 'peekaboo'
In [50]: b_list
Out[50]: ['foo', 'red', 'baz', 'dwarf']
In [51]: b_list.append('foo')
In [52]: b_list
Out[52]: ['foo', 'red', 'baz', 'dwarf', 'foo']
In [53]: b_list.remove('foo')
In [54]: b_list
Out[54]: ['red', 'baz', 'dwarf', 'foo']
in:检查列表是否包含某个值:
In [55]: 'dwarf' in b_list
Out[55]: True
extend:列表追加
In [58]: x = [4, None, 'foo']
In [59]: x.extend([7, 8, (2, 3)])
In [60]: x
Out[60]: [4, None, 'foo', 7, 8, (2, 3)]
同样下,extend比用‘+’效率更高。
排序
sort:列表原地排序
In [61]: a = [7, 2, 5, 1, 3]
In [62]: a.sort()
In [63]: a
Out[63]: [1, 2, 3, 5, 7]
#使用key进行排序
In [64]: b = ['saw', 'small', 'He', 'foxes', 'six']
In [65]: b.sort(key=len)
In [66]: b
Out[66]: ['He', 'saw', 'six', 'small', 'foxes']
bisect:二分查找
bisect进行二分查找搜索,但并不检查原队列是否有序
In [67]: import bisect
In [68]: c = [1, 2, 2, 2, 3, 4, 7]
#bisect.bisect 找到应该插入的位置
In [69]: bisect.bisect(c, 2)
Out[69]: 4
In [70]: bisect.bisect(c, 5)
Out[70]: 6
#bisect.insort 向对应位置插入值
In [71]: bisect.insort(c, 6)
In [72]: c
Out[72]: [1, 2, 2, 2, 3, 4, 6, 7]
切片

In [73]: seq = [7, 2, 3, 7, 5, 6, 0, 1]
#可以对某一(几)个元素赋值一个队列
In [75]: seq[3:4] = [6, 3]
In [76]: seq
Out[76]: [7, 2, 3, 6, 3, 5, 6, 0, 1]
#第二个冒号后面使用step,定义步长
In [81]: seq[::2]
Out[81]: [7, 3, 3, 6, 1]
#使用-1,它可以将列表或元组颠倒过来
In [82]: seq[::-1]
Out[82]: [1, 0, 6, 5, 3, 6, 3, 2, 7]
1.3 序列函数
enumerate:返回(i, value)元组序列
#计算序列(唯一的)dict映射到位置的值
In [83]: some_list = ['foo', 'bar', 'baz']
In [84]: mapping = {}
In [85]: for i, v in enumerate(some_list):
....: mapping[v] = i
In [86]: mapping
Out[86]: {'bar': 1, 'baz': 2, 'foo': 0}
sorted函数:从任意序列的元素返回一个新的排好序的列表
In [87]: sorted([7, 1, 2, 6, 0, 3, 2])
Out[87]: [0, 1, 2, 2, 3, 6, 7]
In [88]: sorted('horse race')
Out[88]: [' ', 'a', 'c', 'e', 'e', 'h', 'o', 'r', 'r', 's']
zip:将多个列表、元组或其它序列 成对组合 成一个元组列表
In [89]: seq1 = ['foo', 'bar', 'baz']
In [90]: seq2 = ['one', 'two', 'three']
In [91]: zipped = zip(seq1, seq2)
In [92]: list(zipped)
Out[92]: [('foo', 'one'), ('bar', 'two'), ('baz', 'three')]
# 与enumerate结合使用
In [95]: for i, (a, b) in enumerate(zip(seq1, seq2)):
....: print('{0}: {1}, {2}'.format(i, a, b))
....:
0: foo, one
1: bar, two
2: baz, three
#可用于解压序列,把列表按列拆出来
In [96]: pitchers = [('Nolan', 'Ryan'), ('Roger', 'Clemens'),('Schilling', 'Curt')]
In [97]: first_names, last_names = zip(*pitchers)
In [98]: first_names
Out[98]: ('Nolan', 'Roger', 'Schilling')
In [99]: last_names
Out[99]: ('Ryan', 'Clemens', 'Curt')
reversed:可以从后向前迭代一个序列
In [100]: list(reversed(range(10)))
Out[100]: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
reversed是一个生成器,只有实体化(即列表或for循环)之后才能创建翻转的序列。
1.4 字典
键值对的大小可变集合,使用尖括号创立
字典的键必须为不可变类型,列表不可以作为字典的键
In [101]: empty_dict = {}
In [102]: d1 = {'a' : 'some value', 'b' : [1, 2, 3, 4]}
In [103]: d1
Out[103]: {'a': 'some value', 'b': [1, 2, 3, 4]}
In [104]: d1[7] = 'an integer'
In [105]: d1
Out[105]: {'a': 'some value', 'b': [1, 2, 3, 4], 7: 'an integer'}
In [107]: 'b' in d1
Out[107]: True
del和pop() 根据键来删除值
pop()会输出删除的对应 值
keys和values是字典的键和值的迭代器方法
In [116]: d1
Out[116]: {'a': 'some value', 'b': [1, 2, 3, 4], 7: 'an integer'}
In [117]: list(d1.keys())
Out[117]: ['a', 'b', 7]
In [118]: list(d1.values())
Out[118]: ['some value', [1, 2, 3, 4], 'an integer']
update:将一个字典与另一个融合
若相同,原字典旧值呗覆盖
In [119]: d1.update({'b' : 'foo', 'c' : 12})
In [120]: d1
Out[120]: {'a': 'some value', 'b': 'foo', 7: 'an integer', 'c': 12}
将两个序列配对组合成字典
mapping = {}
for key, value in zip(key_list, value_list):
mapping[key] = value
关于默认值:
字典.get(key,defalut)
if key in some_dict:
value = some_dict[key]
else:
value = default_value
#可以替换为:
value = some_dict.get(key, default_value)
#按首字母分类
In [123]: words = ['apple', 'bat', 'bar', 'atom', 'book']
In [124]: by_letter = {}
In [125]: for word in words:
.....: letter = word[0]
.....: if letter not in by_letter:
.....: by_letter[letter] = [word]
.....: else:
.....: by_letter[letter].append(word)
.....:
In [126]: by_letter
Out[126]: {'a': ['apple', 'atom'], 'b': ['bat', 'bar', 'book']}
等价为:
for word in words
letter=word[0]
by_letter.setdefault(letter,[]).append(word)
1.5集合
无序的、不可重复、可以看作是只有键没有值的字典。
set:创立(或使用尖括号
In [133]: set([2, 2, 2, 1, 3, 3])
Out[133]: {1, 2, 3}
In [134]: {2, 2, 2, 1, 3, 3}
Out[134]: {1, 2, 3}
合并:union 或 ’|‘
交集:intersection或 ‘&’
集合运算:

1.6 列表、集合和字典推导式
从一个集合过滤元素,形成列表(集合、字典)
列表:
[expr for val in collection if condition]
例:
In [154]: strings = ['a', 'as', 'bat', 'car', 'dove', 'python']
In [155]: [x.upper() for x in strings if len(x) > 2]
Out[155]: ['BAT', 'CAR', 'DOVE', 'PYTHON']
字典:
dict_comp = {key-expr : value-expr for value in collection if condition}
集合:
set_comp = {expr for value in collection if condition}
In [154]: strings = ['a', 'as', 'bat', 'car', 'dove', 'python']
In [156]: unique_lengths = {len(x) for x in strings}
In [157]: unique_lengths
Out[157]: {1, 2, 3, 4, 6}
#map函数可以进一步简化
#map(function, iterable, ...) 参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
In [158]: set(map(len, strings))
Out[158]: {1, 2, 3, 4, 6}
本文介绍了Python中基本的数据结构,包括元组、列表、字典和集合的使用,包括它们的特点、常用操作如创建、修改、遍历、排序等,并展示了如何通过列表推导式和集合推导式进行数据处理。此外,还提到了一些实用的序列函数,如enumerate、sorted和zip。通过这些基础知识的学习,能快速上手Python的数据分析工作。
2051

被折叠的 条评论
为什么被折叠?



