您的位置:首页 > 编程语言 > Python开发

数据分析学习-第五课 numpy读取本地数据和索引(第2-3节)(有相应课件视频下载链接在文末)

2019-05-19 15:25 381 查看

第五课

第2节 numpy中的索引和切片
这一节是重点内容,用的特别多

import numpy as np
t1 = np.array(range(100)).reshape(20,5)
# print(t1)
#取第二行
# print(t1[1])

#取不连续的几行
# print(t1[[2,8,10]])

#取连续的列
# print(t1[2,:])
#取1,2,7行
# print(t1[[1,2,7],:])
# 取第1,2列
# print(t1[:,[1,2]])
#取第一行以后的行
# print(t1[1:,:])
#取某列
# print(t1[:,1])
# 取连续的数列
# print(t1[:,2:])
# 取不连续的数列
# print(t1[:,[2,4]])
#取某一行某一列的值
# print(t1[2,3])

#取多行多列,连续列连续行
# print(t1[2:5,1:4])

#取多个不相邻的点
# print(t1[[0,2],[1,3]])#取了【0,1】和【2,3】这两个值

#取不同的连续列
# print(t1[:,0:4:2])
# print(t1[:,0::2])#2为步长
# print(t1[:,0::1])

注意几个常用的方式:
#取不连续的几行
#print(t1[[2,8,10]])
#取1,2,7行
#print(t1[[1,2,7],:])
#取第一行以后的行
#print(t1[1:,:])
#取多行多列,连续列连续行
#print(t1[2:5,1:4])

#取多个不相邻的点----注意易出错
#print(t1[[0,2],[1,3]])#取了【0,1】和【2,3】这两个值

#取不连续的几行
#print(t1[[2,8,10]])

#取不同的连续列
print(t1[:,0::2])#2为步长

行和列是以“,”分开的,在“,”的两边可以如下操作:(1行之后的所有行/2-4行/0-2-4行/0行之后的行,每隔2行取一次即0-2-4-6-8…)1:/2:4/0:5:2/0::2等操作。

第3节 numpy中更多的索引方式
关键点:np.where/t.clip/nan

>>>import numpy as np
>>>t1 = np.array(range(24)).reshape(4,6)
>>>print(t1)

[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]
[12 13 14 15 16 17]
[18 19 20 21 22 23]]

>>>t1[:,2:4] = 0
>>>print(t1)

[[ 0 1 0 0 4 5]
[ 6 7 0 0 10 11]
[12 13 0 0 16 17]
[18 19 0 0 22 23]]

import numpy as np
t1 = np.array(range(24)).reshape(4,6)
t1[t1>10] = 0
print(t1)

[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 0]
[ 0 0 0 0 0 0]
[ 0 0 0 0 0 0]]

import numpy as np
t1 = np.array(range(24)).reshape(4,6)
print(t1)
print(t1<10)

[[ True True True True True True]
[ True True True True False False]
[False False False False False False]
[False False False False False False]]

import numpy as np
t1 = np.array(range(24)).reshape(4,6)
t1[t1>20]

array([21, 22, 23])

t1[t1>20]=20
print(t1)

[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]
[12 13 14 15 16 17]
[18 19 20 20 20 20]]

三元运算-np.where/t.clip

import numpy as np
t1 = np.array(range(24)).reshape(4,6)
t2 = np.where(t1<10,0,10)
print(t2)

[[ 0 0 0 0 0 0]
[ 0 0 0 0 10 10]
[10 10 10 10 10 10]
[10 10 10 10 10 10]]

clip运算:
clip小于10替换成10,大于18替换成18,中间不变

import numpy as np
t1 = np.array(range(24)).reshape(4,6)
t1.clip(10,18)

array([[10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 18, 18, 18, 18, 18]])

import numpy as np
t1 = np.array(range(24)).reshape(4,6)
t2 = t1.clip(10,18)
t2[3,3] = np.nan
ValueError  Traceback (most recent call last) <ipython-input-11-489596db68dd> in <module>()
3 t2 = t1.clip(10,18)
4
----> 5 t2[3,3] = np.nan

ValueError: cannot convert float NaN to integer

因为:nan是float类型,不能转化成整型int
所以续作如下修改:

import numpy as np
t1 = np.array(range(24)).reshape(4,6)
t2 = t1.clip(10,18)
t2 = t2.astype(float)
t2[3,3]=np.nan
print(t2)

[[ 10. 10. 10. 10. 10. 10.]
[ 10. 10. 10. 10. 10. 11.]
[ 12. 13. 14. 15. 16. 17.]
[ 18. 18. 18. nan 18. 18.]]

链接:https://pan.baidu.com/s/1EvfAJ9UttzlfgdlrbJlfQQ
提取码:qf3c

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐