目录
1,numpy
Numpy
Numpy切片操作
data = data_original.iloc[:,1:2]结果为DataFrame
data = data_original.iloc[:,2] 结果为Serise
data_25 =data[0]
arr[1:2, 1:3]
np.c_和np.c_
np.c_是按行连接两个矩阵,就是把两矩阵上下相加,要求行数相等,类似于pandas中的concat()
np.c_是按列连接两个矩阵,就是把两矩阵左右相加,要求列数相等,类似于pandas中的merge()
Numpy随机数
x = np.linspace(start,stop,num)(默认num等于50)
numpy的ones_like函数/np.zeros
返回一个用1填充的跟输入 形状和类型 一致的数组。
>>> x = np.arange(6)
>>> x = x.reshape((2, 3))
>>> x
array([[0, 1, 2],
[3, 4, 5]])
>>> np.ones_like(x)
array([[1, 1, 1],
[1, 1, 1]])
>>>
>>> y = np.arange(3, dtype=np.float)
>>> y
array([ 0., 1., 2.])
>>> np.ones_like(y)
array([ 1., 1., 1.])
同理,zeros_like返回一个用0填充的跟输入数组 形状和类型一样的数组。
range() 与 np.arange()
>>>range(1,5)
range(1,5)
>>>tuple(range(1, 5))
(1, 2, 3, 4)
>>>list(range(1, 5))
[1, 2, 3, 4]
>>>r = range(1, 5)
>>>type(r)
<class 'range'>
>>>for i in range(1, 5):
... print(i)
1
2
3
4
>>> np.arange(1, 5)
array([1, 2, 3, 4])
>>>range(1, 5, .1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
>>>np.arange(1, 5, .5)
array([ 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5])
>>>range(1, 5, 2)
>>>for i in range(1, 5, 2):
... print(i)
1
3
>>for i in np.arange(1, 5):
... print(i)
1
2
3
4
Python中的shape()和reshape()
参考博文:https://blog.youkuaiyun.com/qq_28618765/article/details/78083895
shape()和reshape()都是数组array中的方法
- shape()
import numpy as np
a = np.array([1,2,3,4,5,6,7,8]) #
一维数组
print(a.shape[0]) #
值为
8
,因为有
8
个数据
print(a.shape[1]) #IndexError: tuple index out of range
a = np.array([[1,2,3,4],[5,6,7,8]]) #
二维数组
print(a.shape[0]) #
值为
2
,最外层矩阵有
2
个元素,
2
个元素还是矩阵。
print(a.shape[1]) #
值为
4
,内层矩阵有
4
个元素。
print(a.shape[2]) #IndexError: tuple index out of range
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- reshape()
reshape新生成数组和原数组公用一个内存,不管改变哪个都会互相影响。
numpy.random详细解析
https://blog.youkuaiyun.com/vicdd/article/details/52667709
numpy- shape用法
建立一个4×2的矩阵c, c.shape[1] 为第一维的长度,c.shape[0] 为第二维的长度
- c = array([[1,1],[1,2],[1,3],[1,4]])
- >>> c.shape
- (4, 2)
- >>> c.shape[0]
- 4
- >>> c.shape[1]
- 2
所谓元素,在一维时就是元素的个数,二维时表示行数和列数,三维时a.shape【0】表示创建的块数,a.shape【1】和a.shape【2】表示每一块(每一块都是二维的)的行数和列数,
numpy.argmin
表示最小值在数组中所在的位置
hstack(value)将数组合并
https://blog.youkuaiyun.com/garfielder007/article/details/51378296
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.hstack((a,b))
array([1, 2, 3, 2, 3, 4])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.hstack((a,b))
array([[1, 2],
[2, 3],
[3, 4]])
numpy.diff
numpy.diff(a,n = 1,轴= -1 )
n等于多少,就进行几次差分计算
计算沿给定轴的第n个离散差。
第一个差异是沿着给定的轴给出的,通过 递归使用来计算更高的差异。out[i] = a[i+1] - a[i]
2.Pandas
Pandas
DataFrame切片操作iloc
loc使用标签取值
data = data.as_matrix() #将表格转换为矩阵
https://jingyan.baidu.com/article/a17d52853f879e8099c8f240.html
Pandas统计特征函数
主要作为Pandas的对象DataFrame或Series的方法出现。
sum():计算数据样本的总和(按列计算)
mean():计算数据样本的算术平均数
var():计算数据样本的方差
std():计算数据样本的标准差
corr():计算数据样本的Spearman(Pearson)相关系数矩阵
pandas常用函数
http://www.cnblogs.com/hotsnow/p/9480849.html
pandas库pd.read_excel参数
https://blog.youkuaiyun.com/brucewong0516/article/details/79096633
pd.read_excel(io, sheetname=0,header=0,skiprows=None,index_col=None,names=None,
arse_cols=None,date_parser=None,na_values=None,thousands=None,
convert_float=True,has_index_names=None,converters=None,dtype=None,
true_values=None,false_values=None,engine=None,squeeze=False,**kwds)
- io :excel 路径;
- sheetname:默认是sheetname为0,返回多表使用sheetname=[0,1],若sheetname=None是返回全表 。注意:int/string返回的是dataframe,而none和list返回的是dict of dataframe。
- header :指定作为列名的行,默认0,即取第一行,数据为列名行以下的数据;若数据不含列名,则设定 header = None
- skiprows:省略指定行数的数据
- skip_footer:省略从尾部数的行数据
- index_col :指定列为索引列,也可以使用 u’string’
- names:指定列的名字,传入一个list数据
重置index
data= data.reset_index(drop=True)
Python将DataFrame的某一列作为index
df.set_index(["Column"], inplace=True)
pandas.read_csv参数详解
def parse(x):
return datetime.strptime(x, '%Y %m %d %H')
dataset = read_csv('C:/Users/kyle/Desktop/raw.csv', parse_dates = [['year', 'month', 'day', 'hour']], index_col=0, date_parser=parse)
第一步是将日期时间信息合并为一个日期时间,以便我们可以将其用作Pandas中的索引。
parse_dates将年月日小时合并为一个日期,index_col=0将第一列作为索引
pandas.DataFrame.dropna
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html
DataFrame.dropna(axis = 0,how ='any',thresh = None,subset = None,inplace = False )
删除缺失的值。
pandas中shift和diff
①对于DataFrame的行索引是日期型,行索引发生移动,列索引数据不变
In [2]: import pandas as pd
...: import numpy as np
...: df = pd.DataFrame(np.arange(24).reshape(6,4),index=pd.date_range(start=
...: '20170101',periods=6),columns=['A','B','C','D'])
...: df
...:
Out[2]:
A B C D
2017-01-01 0 1 2 3
2017-01-02 4 5 6 7
2017-01-03 8 9 10 11
2017-01-04 12 13 14 15
2017-01-05 16 17 18 19
2017-01-06 20 21 22 23
In [3]: df.shift(2,axis=0,freq='2D')
Out[3]:
A B C D
2017-01-05 0 1 2 3
2017-01-06 4 5 6 7
2017-01-07 8 9 10 11
2017-01-08 12 13 14 15
2017-01-09 16 17 18 19
2017-01-10 20 21 22 23
In [4]: df.shift(2,axis=1,freq='2D')
Out[4]:
A B C D
2017-01-05 0 1 2 3
2017-01-06 4 5 6 7
2017-01-07 8 9 10 11
2017-01-08 12 13 14 15
2017-01-09 16 17 18 19
2017-01-10 20 21 22 23
In [5]: df.shift(2,freq='2D')
Out[5]:
A B C D
2017-01-05 0 1 2 3
2017-01-06 4 5 6 7
2017-01-07 8 9 10 11
2017-01-08 12 13 14 15
2017-01-09 16 17 18 19
2017-01-10 20 21 22 23
结论:对于时间索引而言,shift使时间索引发生移动,其他数据保存原样,且axis设置没有任何影响
②对于DataFrame行索引为非时间序列,行索引数据保持不变,列索引数据发生移动
In [6]: import pandas as pd
...: import numpy as np
...: df = pd.DataFrame(np.arange(24).reshape(6,4),index=['r1','r2','r3','r4'
...: ,'r5','r6'],columns=['A','B','C','D'])
...: df
...:
Out[6]:
A B C D
r1 0 1 2 3
r2 4 5 6 7
r3 8 9 10 11
r4 12 13 14 15
r5 16 17 18 19
r6 20 21 22 23
In [7]: df.shift(periods=2,axis=0)
Out[7]:
A B C D
r1 NaN NaN NaN NaN
r2 NaN NaN NaN NaN
r3 0.0 1.0 2.0 3.0
r4 4.0 5.0 6.0 7.0
r5 8.0 9.0 10.0 11.0
r6 12.0 13.0 14.0 15.0
In [8]: df.shift(periods=-2,axis=0)
Out[8]:
A B C D
r1 8.0 9.0 10.0 11.0
r2 12.0 13.0 14.0 15.0
r3 16.0 17.0 18.0 19.0
r4 20.0 21.0 22.0 23.0
r5 NaN NaN NaN NaN
r6 NaN NaN NaN NaN
In [9]: df.shift(periods=2,axis=1)
Out[9]:
A B C D
r1 NaN NaN 0.0 1.0
r2 NaN NaN 4.0 5.0
r3 NaN NaN 8.0 9.0
r4 NaN NaN 12.0 13.0
r5 NaN NaN 16.0 17.0
r6 NaN NaN 20.0 21.0
In [10]: df.shift(periods=-2,axis=1)
Out[10]:
A B C D
r1 2.0 3.0 NaN NaN
r2 6.0 7.0 NaN NaN
r3 10.0 11.0 NaN NaN
r4 14.0 15.0 NaN NaN
r5 18.0 19.0 NaN NaN
r6 22.0 23.0 NaN NaN
下面看看diff函数和shift函数之间的关系
In [13]: df.diff(periods=2,axis=0)
Out[13]:
A B C D
r1 NaN NaN NaN NaN
r2 NaN NaN NaN NaN
r3 8.0 8.0 8.0 8.0
r4 8.0 8.0 8.0 8.0
r5 8.0 8.0 8.0 8.0
r6 8.0 8.0 8.0 8.0
In [14]: df -df.diff(periods=2,axis=0)
Out[14]:
A B C D
r1 NaN NaN NaN NaN
r2 NaN NaN NaN NaN
r3 0.0 1.0 2.0 3.0
r4 4.0 5.0 6.0 7.0
r5 8.0 9.0 10.0 11.0
r6 12.0 13.0 14.0 15.0
In [15]: df.shift(periods=2,axis=0)
Out[15]:
A B C D
r1 NaN NaN NaN NaN
r2 NaN NaN NaN NaN
r3 0.0 1.0 2.0 3.0
r4 4.0 5.0 6.0 7.0
r5 8.0 9.0 10.0 11.0
r6 12.0 13.0 14.0 15.0
pandas.DataFrame.drop
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html
DataFrame.drop(labels = None,axis = 0,index = None,columns = None,level = None,inplace = False,errors ='raise' )[source]
从行或列中删除指定的标签。
Pandas+groupby用法讲解
相当于按照某一列,把相同的组合起来,再进行操作
In [4]:df = pd.DataFrame({'A': ['a', 'b', 'a', 'c', 'a', 'c', 'b', 'c'] , 'B': [2, 8, 1, 4, 3, 2, 5, 9], 'C': [102, 98, 107, 104, 115, 87, 92, 123]})
In [5]:df
Out[5]:
A B C
0 a 2 102
1 b 8 98
2 a 1 107
3 c 4 104
4 a 3 115
5 c 2 87
6 b 5 92
7 c 9 123
In [6]: df.groupby('A').mean()
Out[6]:
B C
A
a 2.0 108.000000
b 6.5 95.000000
c 5.0 104.666667
In [7]: df.groupby(['A','B']).mean()
Out[7]:
C
A B
a 1 107
2 102
3 115
b 5 92
8 98
c 2 87
4 104
9 123
DataFrame 类型转换方法—astype()
df['col2'] = df['col2'].astype('int')
df['col2'] = df['col2'].astype('float64')
data_2=data_1.values
data_2=np.array(data_2,dtype=np.float) #将int转float
DataFrame.rolling
在建模过程中,我们常常需要需要对有时间关系的数据进行整理。比如我们想要得到某一时刻过去30分钟的销量(产量,速度,消耗量等),传统方法复杂消耗资源较多,pandas提供的rolling使用简单,速度较快。
DataFrame.rolling(window, min_periods=None, freq=None, center=False, win_type=None, on=None, axis=0, closed=None)
window:表示时间窗的大小,注意有两种形式(int or offset)。如果使用int,则数值表示计算统计量的观测值的数量即向前几个数据。如果是offset类型,表示时间窗的大小。pandas offset相关可以参考这里。
min_periods:最少需要有值的观测点的数量,对于int类型,默认与window相等。对于offset类型,默认为1。
freq:从0.18版本中已经被舍弃。
center:是否使用window的中间值作为label,默认为false。只能在window是int时使用。
win_type:窗口类型,默认为None一般不特殊指定,了解支持的其他窗口类型,参考这里。
on:对于DataFrame如果不使用index(索引)作为rolling的列,那么用on来指定使用哪列。
closed:定义区间的开闭,曾经支持int类型的window,新版本已经不支持了。对于offset类型默认是左开右闭的即默认为right。可以根据情况指定为left both等。
axis:方向(轴),一般都是0。
https://blog.youkuaiyun.com/wj1066/article/details/78853717
pandas.resample()
附:常见时间频率
A year
M month
W week
D day
H hour
T minute
S second
ts_5d_leftclosed = ts.resample('5D', closed='right').sum()
print(ts_5d_leftclosed)
首先先来创建一个时间序列,起始日期是2018/01/01,一共12天,每天对应的数值分别是1到12:
使用resample方法来做降采样处理,频率是5天,上面提到的两个参数,都使用默认值:
ts_5d = ts.resample('5D').sum()
print(ts_5d)
#### Outputs ####
2018-01-01 15
2018-01-06 40
2018-01-11 23
Freq: 5D, dtype: int32
closed = 'left' 左闭右开
上面的三个5天可以由以下的三个左闭右开的区间构成:
- 区间1:[1, 6)
- 区间2: [6, 11)
- 区间3:[11, 16) 例子中,时间只到12号为止,但是这里会往后补足5天
closed = 'right' 左开右闭
上面的三个5天可以由以下的四个左开右闭的区间构成。注意,由于第一个5天是从1号到6号,但由于是左开区间,1号就落不到1到6号的那个区间,所以要往前补足:
- 区间1:(27, 1]
- 区间2:(1, 6]
- 区间3: (6, 11]
- 区间4:(11, 16]
closed:划分区间的依据,left会划成左闭右开区间;right会划分成左开右闭的区间。一般来说,closed为right的时候,区间会比为left的时候多一个。区间划分完毕,聚合运算就在这个区间内执行。
label:划分区间完毕,根据label的不同,区间的索引就不同。如果label为left,则区间左边的日期作为索引;如果label为right,则区间右边的日期作为索引。