Python学习(2)-做数据分析

2015-10-21  本文已影响0人  杜七

Author: 杜七


一、基础类型变量的赋值等等

1,数组赋值和操作

>>> import numpy as np
>>> a = np.array([1,2,3,4])
>>> a.dtype # 数组类型
dtype('int32')
>>> a 
array([1, 2, 3, 4])
>>> a.shape # 数组大小
(4,)

>>> c.shape = 4,3
>>> c
array([[ 1,  2,  3],
   [ 4,  4,  5],
   [ 6,  7,  7],
   [ 8,  9, 10]])

 >>> a[0] # Python的subindex从0开始
1

>>> np.array([[1, 2, 3, 4],[4, 5, 6, 7], [7, 8, 9, 10]], dtype=np.float) # 可以制定元素的类型

>>> a[1:-1:2] # 范围中的第三个参数表示步长,2表示隔一个元素取一个元素

>>> x = np.arange(5,0,-1)
>>> x
array([5, 4, 3, 2, 1])
>>> x[np.array([True, False, True, False, False])]

x = np.random.rand(10) # 产生一个长尾为10,元素值为0-1的随机数组

2,更快的数组赋值

上面都是先创建一个python序列,然后通过array函数来转化,效率比较低。NUmpy里面也有专门的创建数组的函数,比如:

np.arrange(0,1,0.1) # 不包括end值

np.linspace(0,1,12) # 包括end值

还可以使用frombuffer, fromstring,fromfile等函数可以从字节序列创建数组,比如:

s="Hello world!"
np.fromstring(s,dtype=np.char)

>>> def func(i):
return i%4+1

>>> np.fromfunction(func, (10,))
array([ 1., 2., 3., 4., 1., 2., 3., 4., 1., 2.])

##结构数组,创建一个dtype的persontype
persontype = np.dtype({
'names':['name', 'age', 'weight'],
'formats':['S32','i', 'f']})

a = np.array([("Zhang",32,75.5),("Wang",24,65.2)],
dtype=persontype) # 

二、画图

1)matplotlib画图

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,10,1000)
y = np.sin(x)
z = np.cox(x**2)

plt.figure(figsize = (8,4)) # 创建画图对象
plt.plot(x,y,label="$sin(x)$",color="red",linewidth=2)
plt.plot(x,z,"b--",label="$con(x^2)$")
plt.xlabel("Times(s)")
plt.ylabel("Volt")
plt.title("Pyplot first example")
plt.ylim(-1,2,1.2)
plt.legend()
plt.show()
上一篇 下一篇

猜你喜欢

热点阅读