Pandas快速上手(一):基本 *** 作NumPy基本 *** 作快速熟悉

Pandas快速上手(一):基本 *** 作NumPy基本 *** 作快速熟悉,第1张

概述本文包含一些 Pandas 的基本 *** 作,旨在快速上手 Pandas 的基本 *** 作。 读者最好有 NumPy 的基础,如果你还不熟悉 NumPy,建议您阅读NumPy基本 *** 作快速熟悉。 Pandas 数据

本文包含一些 Pandas 的基本 *** 作,旨在快速上手 Pandas 的基本 *** 作。

读者最好有 NumPy 的基础,如果你还不熟悉 NumPy,建议您阅读NumPy基本 *** 作快速熟悉。

Pandas 数据结构

Pandas 有两个核心的数据结构:SerIEsDataFrame

SerIEs

SerIEs 是一维的类数组对象,包含一个值序列以及对应的索引

1 obj = pd.SerIEs([6,66,666,6666])2 obj
0       61      662     6663    6666dtype: int64

此时索引默认为 0 到 N。我们可以分别访问 SerIEs 的值和索引:

1 obj.values2 obj.index  # 类似于 range(4)
array([   6,6666])RangeIndex(start=0,stop=4,step=1)

索引可以用标签来指定:

1 obj2 = pd.SerIEs([6,6666],index=['d',bac'2 obj23 obj2.index
d       6b      66a     666c    6666dtype: int64Index(['d','b','a','c'],dtype='object')

可以使用标签索引来访问 SerIEs 的值,这有点像 NumPy 和字典的结合。

1 obj2[]2 obj2['] = 666663 obj2[[']]
666c     6666a      666d    66666dtype: int64

SerIEs 可以使用很多类似于 NumPy 的 *** 作:

1 obj2[obj2 > 1002 obj2 / 23 np.sqrt(obj2)
d    66666a      666c     6666dtype: int64d    33333.0b       33.0a      333.0c     3333.0dtype: float64d    258.197599b      8.124038a     25.806976c     81.645576dtype: float64

判断某索引是否存在:

1 ' in obj22 ein obj2
TrueFalse

可以直接将字典传入 SerIEs 来创建 SerIEs 对象:

1 sdata = {Ohio': 35000,1)">Texas': 71000,1)">Oregon': 16000,1)">Utah': 5000}2 obj3 = pd.SerIEs(sdata)3 obj34 states = [California5 obj4 = pd.SerIEs(sdata,index=states)   指定了索引及其顺序6 obj4
Ohio      35000Texas     71000Oregon    16000Utah       5000dtype: int64Texas         71000.0California        NaNOhio          35000.0Oregon        16000.0dtype: float64

通过 isnullnotnull 可以检测是否有空值,既可以使用 Pandas 函数也可以使用 SerIEs 方法:

pd.isnull(obj4)pd.notnull(obj4)obj4.isnull()4 obj4.notnull()
Texas         FalseCalifornia     TrueOhio          FalseOregon        Falsedtype: boolTexas          TrueCalifornia    FalseOhio           TrueOregon         Truedtype: boolTexas         FalseCalifornia     TrueOhio          FalseOregon        Falsedtype: boolTexas          TrueCalifornia    FalseOhio           TrueOregon         Truedtype: bool

SerIEs 的数据对齐,类似于数据库的连接 *** 作:

obj43 obj3 + obj4
Ohio      35000Texas     71000Oregon    16000Utah       5000dtype: int64Texas         71000.0California        NaNOhio          35000.0Oregon        16000.0dtype: float64California         NaNOhio           70000.0Oregon         32000.0Texas         142000.0Utah               NaNdtype: float64

SerIEs 及其索引都有一个 name 属性:

1 obj4.name = population'2 obj4.index.name = state3 obj4
stateTexas         71000.0California        NaNOhio          35000.0Oregon        16000.0name: population,dtype: float64

SerIEs 的索引可以原地(in-place)修改:

obj2 obj.index = [BobSteveJeffRyan3 obj
0       61      662     6663    6666dtype: int64Bob         6Steve      66Jeff      666Ryan     6666dtype: int64
DataFrame

DataFrame 表示一张矩阵数据表,其中包含有序的列集合,每列都可以表示不同的数据类型。

DataFrame 有行索引和列索引,可以把它当做是 SerIEs 的字典,该字典共享同一套行索引。

通过等长列表(或 NumPy 数组)的字典是常用的创建方式:

 每个值都是长度为 6 的列表2 data = {3     ': [Nevada],4     year': [2000,2001,2002,20035     pop': [2.5,1.7,3.6,2.4,2.9,3.26 7 frame = pd.DataFrame(data)8 data
	state	year	pop0	Ohio	2000	2.51	Ohio	2001	1.72	Ohio	2002	3.63	Nevada	2001	2.44	Nevada	2002	2.95	Nevada	2003	3.2

通过 head 方法可以选择前几行:

frame.head()2 frame.head(2)
	state	year	pop0	Ohio	2000	2.51	Ohio	2001	1.72	Ohio	2002	3.63	Nevada	2001	2.44	Nevada	2002	2.9
state year pop0 Ohio 2000 2.51 Ohio 2001 1.7

指定列的序列,可以按照响应顺序来展示:

1 pd.DataFrame(data,columns=['])
	year	state	pop0	2000	Ohio	2.51	2001	Ohio	1.72	2002	Ohio	3.63	2001	Nevada	2.44	2002	Nevada	2.95	2003	Nevada	3.2

同样也可以指定索引:

1 frame2 = pd.DataFrame(data,1)">debt2                      index=[onetwothreefourfivesixframe24 frame2.columns5 frame2.index
	year	state	pop	debtone	2000	Ohio	2.5	NaNtwo	2001	Ohio	1.7	NaNthree	2002	Ohio	3.6	NaNfour	2001	Nevada	2.4	NaNfive	2002	Nevada	2.9	NaNsix	2003	Nevada	3.2	NaNIndex(['year','state','pop','debt'],dtype='object')Index(['one','two','three','four','five','six'],dtype='object')

通过键或者属性提取 DataFrame 的一列,得到的是 SerIEs:

1 frame2[frame2.year3 type(frame2.year)
one        Ohiotwo        Ohiothree      Ohiofour     Nevadafive     Nevadasix      Nevadaname: state,dtype: objectone      2000two      2001three    2002four     2001five     2002six      2003name: year,dtype: int64pandas.core.serIEs.SerIEs

通过 loc 属性可以指定标签,检索行数据:

1 frame2.loc[2 type(frame2.loc['])
year     2002state    Ohiopop       3.6debt      NaNname: three,dtype: objectpandas.core.serIEs.SerIEs

对 'debt' 列进行赋值:

'] = 16.53 frame2['] = np.arange(6.)4 frame2
     year	state	pop	debtone	2000	Ohio	2.5	16.5two	2001	Ohio	1.7	16.5three	2002	Ohio	3.6	16.5four	2001	Nevada	2.4	16.5five	2002	Nevada	2.9	16.5six	2003	Nevada	3.2	16.5     year	state	pop	debtone	2000	Ohio	2.5	0.0two	2001	Ohio	1.7	1.0three	2002	Ohio	3.6	2.0four	2001	Nevada	2.4	3.0five	2002	Nevada	2.9	4.0six	2003	Nevada	3.2	5.0

可以用 SerIEs 来赋值 DataFrame 列:

1 val = pd.SerIEs([-1.2,-1.5,-1.7],1)">2 frame2['] = val3 frame2
	year	state	pop	debtone	2000	Ohio	2.5	NaNtwo	2001	Ohio	1.7	-1.2three	2002	Ohio	3.6	NaNfour	2001	Nevada	2.4	-1.5five	2002	Nevada	2.9	-1.7six	2003	Nevada	3.2	NaN

给不存在的列赋值会创建新列:

eastern'] = frame2.state == 2 frame2
	year	state	pop	debt	easternone	2000	Ohio	2.5	NaN	Truetwo	2001	Ohio	1.7	-1.2	Truethree	2002	Ohio	3.6	NaN	Truefour	2001	Nevada	2.4	-1.5	Falsefive	2002	Nevada	2.9	-1.7	Falsesix	2003	Nevada	3.2	NaN	False

删除某列:

del frame2[]frame2.columns
Index(['year',dtype='object')

DataFrame 取出来的列是底层数据的视图,不是拷贝。所做的修改会反映到底层数据中,如果要拷贝必须使用显式的 copy 方法。

传入嵌套字典的情况:

 1 pop = 2     : { 3         2001: 2.4,1)"> 4         2002: 2.9 5     },1)"> 6      7         2000: 1.5 8         2001: 1.7 9         2002: 3.610     }11 12 frame3 =  pd.DataFrame(pop)13 frame3
	Nevada	Ohio2000	NaN	1.52001	2.4	1.72002	2.9	3.6

DataFrame 的转置:

1 frame3.T
	2000	2001	2002Nevada	NaN	2.4	2.9Ohio	1.5	1.7	3.6

values 属性是包含 DataFrame 值的 ndarray:

1 frame3.values
array([[nan,1.5],[2.4,1.7],[2.9,3.6]])
索引对象

Pandas 的索引对象用于存储轴标签元数据(轴名称等)。

1 obj = pd.SerIEs(range(3),1)">2 index = obj.indexindex4 index.name = Alpha5 index[1:]
Index(['a',dtype='object')Index(['b',dtype='object',name='Alpha')

索引对象是不可变对象,因此不可修改:

1 index[1] = '   报错

索引类似于固定长度的集合:

frame3frame3.columnsframe3.index 类似于集合5  frame3.columns6 2000 in frame3.index
Nevada	Ohio2000	NaN	1.52001	2.4	1.72002	2.9	3.6Index(['Nevada','Ohio'],dtype='object')Int64Index([2000,2002],dtype='int64')TrueTrue

但是索引和集合的不同之处是可以包含重复的标签:

1 dup_labels = pd.Index([foobardup_labels3 set_labels = set([4 set_labels
Index(['foo','foo','bar','bar'],dtype='object'){'bar','foo'}

索引对象的一些常用方法:

appenddifferenceintersectionunionisindeletedropinsertis_monotonicis_uniqueuniquePandas 基本功能重新索引

reindex 用于创建一个新对象,其索引进行了重新编排。

1 obj = pd.SerIEs([4.5,7.2,-5.3,3.6],1)">3 obj2 = obj.reindex([4 obj2
d    4.5b    7.2a   -5.3c    3.6dtype: float64a   -5.3b    7.2c    3.6d    4.5e    NaNdtype: float64

ffill 用于向前填充值,在重新索引时会进行插值:

1 obj3 = pd.SerIEs([bluepurpleyellow'],index=[0,2,43 obj3.reindex(range(6),method=ffill')
0      blue2    purple4    yellowdtype: object0      blue1      blue2    purple3    purple4    yellow5    yellowdtype: object

无论行索引还是列索引都可以重新编排:

1 frame = pd.DataFrame(np.arange(9).reshape((3,3)),1)">3                      columns=[frame5 frame.reindex([6 frame.reindex(columns=['])
	Ohio	Texas	Californiaa	0	1	2c	3	4	5d	6	7	8      Ohio	Texas	Californiaa	0.0	1.0	2.0b	NaN	NaN	NaNc	3.0	4.0	5.0d	6.0	7.0	8.0     Texas	Utah	Californiaa	1	NaN	2c	4	NaN	5d	7	NaN	8
根据轴删除数据

使用 drop 方法对数据行或列进行删除:

1 obj = pd.SerIEs(np.arange(5.),1)">3 new_obj = obj.drop()new_obj5 obj.drop(['])
a    0.0b    1.0c    2.0d    3.0e    4.0dtype: float64a    0.0b    1.0d    3.0e    4.0dtype: float64a    0.0b    1.0e    4.0dtype: float64
1 data = pd.DataFrame(np.arange(16).reshape((4,1)">2                     index=[coloradoNew York3                     columns=[data5 data.drop([6 data.drop(7 data.drop([columns')
	one	two	three	fourOhio	0	1	2	3colorado	4	5	6	7Utah	8	9	10	11New York	12	13	14	15     one	two	three	fourUtah	8	9	10	11New York	12	13	14	15     one	three	fourOhio	0	2	3colorado	4	6	7Utah	8	10	11New York	12	14	15     one	threeOhio	0	2colorado	4	6Utah	8	10New York	12	14

原地删除:

2 obj.drop(True)3 obj
a    0.0b    1.0c    2.0d    3.0e    4.0dtype: float64a    0.0b    1.0d    3.0e    4.0dtype: float64
索引、选择、过滤

SerIEs 的索引类似于 NumPy,只不过 SerIEs 还可以用索引标签,不一定是整型索引。

1 obj = pd.SerIEs(np.arange(4.),1)">3 obj[4 obj[15 obj[2:46 obj[[]]7 obj[[1,1)">8 obj[obj < 2]
a    0.0b    1.0c    2.0d    3.0dtype: float641.01.0c    2.0d    3.0dtype: float64b    1.0a    0.0d    3.0dtype: float64b    1.0d    3.0dtype: float64a    0.0b    1.0dtype: float64

SerIEs 的切片和原生 Python 有所不同,是闭区间(Python 是左闭右开区间)。

1 obj[':']
b    1.0c    2.0dtype: float64

使用切片进行赋值:

'] = 52 obj
a    0.0b    5.0c    5.0d    3.0dtype: float64

选择 DataFrame 的若干列:

5 data[6 type(data[7 data[[8 type(data[[']])
     one	two	three	fourOhio	0	1	2	3colorado	4	5	6	7Utah	8	9	10	11New York	12	13	14	15Ohio         1colorado     5Utah         9New York    13name: two,dtype: int64pandas.core.serIEs.SerIEs     three	oneOhio	2	0colorado	6	4Utah	10	8New York	14	12pandas.core.frame.DataFrame

使用切片和布尔数组选择 DataFrame:

1 data[:22 data[data['] > 5]
	one	two	three	fourOhio	0	1	2	3colorado	4	5	6	7        one	two	three	fourcolorado	4	5	6	7Utah	8	9	10	11New York	12	13	14	15

DataFrame 语法上很像二维的 NumPy 数组,使用布尔 DataFrame:

1 data < 52 data[data < 5] = 03 data
	one	two	three	fourOhio	True	True	True	Truecolorado	True	False	False	FalseUtah	False	False	False	FalseNew York	False	False	False	False        one	two	three	fourOhio	0	0	0	0colorado	0	5	6	7Utah	8	9	10	11New York	12	13	14	15
使用 loc 和 iloc 进行选择

lociloc 可以用于选择 DataFrame 的行和列。

1 data.loc[']]
two      5three    6name: colorado,dtype: int64
1 data.iloc[2,[3,12 data.iloc[23 data.iloc[[1,2],1]]
four    11one      8two      9name: Utah,dtype: int64one       8two       9three    10four     11name: Utah,dtype: int64        four	one	twocolorado	7	0	5Utah	11	8	9

同样可以使用切片:

1 data.loc[:2 data.iloc[:,:3][data.three > 5]
Ohio        0colorado    5Utah        9name: two,dtype: int64        one	two	threecolorado	0	5	6Utah	8	9	10New York	12	13	14

DataFrame 常用索引方法:

df[val]:选列df.loc[val]:选行df.loc[:,val]:选列df.loc[val1,val2]:选列和行df.iloc[where]:选行df.iloc[:,where]:选列df.iloc[where_i,where_j]:选列和行df.at[label_i,label_j]:选某一标量df.iat[i,j]:选某一标量reindex:选列和行get_value,set_value:选某一标量算术和数据对齐

前面我们介绍了 SerIEs 的算术对齐,接下来是 DataFrame 的:

1 df1 = pd.DataFrame(np.arange(9.).reshape((3,3)),columns=List(bcd),1)">2                    index=[3 df2 = pd.DataFrame(np.arange(12.).reshape((4,1)">bde4                    index=[5 df1df27 df1 + df2
	b	c	dOhio	0.0	1.0	2.0Texas	3.0	4.0	5.0colorado6.0	7.0	8.0        b	d	eUtah	0.0	1.0	2.0Ohio	3.0	4.0	5.0Texas	6.0	7.0	8.0Oregon	9.0	10.0	11.0        b	c	d	ecoloradoNaN	NaN	NaN	NaNOhio	3.0	NaN	6.0	NaNOregon	NaN	NaN	NaN	NaNTexas	9.0	NaN	12.0	NaNUtah	NaN	NaN	NaN	NaN

没有相同行索引和列索引的情况:

1 df1 = pd.DataFrame({A': [1,2]})2 df2 = pd.DataFrame({B': [3,1)">5 df1 - df2
A0	11	2B0	31	4A	B0	NaN	NaN1	NaN	NaN
填补值的算术方法

对于算术运算后产生空值的情况:

1 df1 = pd.DataFrame(np.arange(12.).reshape((3,1)">2                    columns=List(abcd))3 df2 = pd.DataFrame(np.arange(20.).reshape((4,54                    columns=List(abcde5 df2.loc[1,1)"> np.nan7 8 df1 + df2
	a	b	c	d0	0.0	1.0	2.0	3.01	4.0	5.0	6.0	7.02	8.0	9.0	10.0	11.0        a	b	c	d	e0	0.0	1.0	2.0	3.0	4.01	5.0	NaN	7.0	8.0	9.02	10.0	11.0	12.0	13.0	14.03	15.0	16.0	17.0	18.0	19.0        a	b	c	d	e0	0.0	2.0	4.0	6.0	NaN1	9.0	NaN	13.0	15.0	NaN2	18.0	20.0	22.0	24.0	NaN3	NaN	NaN	NaN	NaN	NaN

可以使用 fill_value 属性来自动填空值:

1 df1.add(df2,fill_value=0)
        a	b	c	d	e0	0.0	2.0	4.0	6.0	4.01	9.0	5.0	13.0	15.0	9.02	18.0	20.0	22.0	24.0	14.03	15.0	16.0	17.0	18.0	19.0

常用的算术方法(可用于补空值):

add,raddsub,rsubdiv,rdivfloordiv,rfloordivmul,rmulpow,rpowDataFrame 和 SerIEs 之间的运算

首先,看看一维数组和二维数组的减法的情况。

1 arr = np.arange(12.).reshape((3,1)">arrarr[0]4 arr - arr[0]
array([[ 0.,1.,2.,3.],[ 4.,5.,6.,7.],[ 8.,9.,10.,11.]])array([0.,3.])array([[0.,0.,0.],[4.,4.,4.],[8.,8.,8.]])

默认情况下,DataFrame 和 SerIEs 会匹配索引进行计算。

1 frame = pd.DataFrame(np.arange(12.).reshape((4,1)">2                      columns=List(3                      index=[4 serIEs = frame.iloc[0]serIEs7 frame - serIEs
        b	d	eUtah	0.0	1.0	2.0Ohio	3.0	4.0	5.0Texas	6.0	7.0	8.0Oregon	9.0	10.0	11.0b    0.0d    1.0e    2.0name: Utah,dtype: float64        b	d	eUtah	0.0	0.0	0.0Ohio	3.0	3.0	3.0Texas	6.0	6.0	6.0Oregon	9.0	9.0	9.0

如果索引不匹配,会用外连接的方式重组索引:

1 serIEs2 = pd.SerIEs(range(3),1)">f2 frame + serIEs2
        b	d	e	fUtah	0.0	NaN	3.0	NaNOhio	3.0	NaN	6.0	NaNTexas	6.0	NaN	9.0	NaNOregon	9.0	NaN	12.0	NaN

如果希望对于所有列进行算术计算(broadcast 机制),必须使用前面介绍的算术方法。

1 serIEs3 = frame[serIEs34 frame.sub(serIEs3,axis=0)
	b	d	eUtah	0.0	1.0	2.0Ohio	3.0	4.0	5.0Texas	6.0	7.0	8.0Oregon	9.0	10.0	11.0Utah       1.0Ohio       4.0Texas      7.0Oregon    10.0name: d,dtype: float64        b	d	eUtah	-1.0	0.0	1.0Ohio	-1.0	0.0	1.0Texas	-1.0	0.0	1.0Oregon	-1.0	0.0	1.0
apply 和 map

NumPy 的通用函数(按元素的数组方法)可以用于 Pandas 对象:

1 frame = pd.DataFrame(np.random.randn(4,3),1)">4 np.abs(frame)
	b	d	eUtah	-0.590458	-0.352861	0.820549Ohio	-1.708280	0.174739	-1.081811Texas	0.857712	0.246972	0.532208Oregon	0.812756	1.260538	0.818304        b	d	eUtah	0.590458	0.352861	0.820549Ohio	1.708280	0.174739	1.081811Texas	0.857712	0.246972	0.532208Oregon	0.812756	1.260538	0.818304

一个常用的 *** 作是按或者调用某一个函数,apply 可以达到该功能:

1 f = lambda x: x.max() - x.min()2 frame.apply(f)
b    2.565993d    1.613398e    1.902360dtype: float64
1 frame.apply(f,axis=1)
Utah      1.411007Ohio      1.883019Texas     0.610741Oregon    0.447782dtype: float64

apply 传入的函数不一定非得返回一个标量值,可以返回 SerIEs:

def f(x):2     return pd.SerIEs([x.min(),x.max()],1)">minmax3 frame.apply(f)
                b	        d	        emin	-1.708280	-0.352861	-1.081811max	0.857712	1.260538	0.820549

还可以传入按元素计算的函数:

2 format = lambda x: %.2f' % x3 frame.applymap(format)
        b	        d	        eUtah	-0.590458	-0.352861	0.820549Ohio	-1.708280	0.174739	-1.081811Texas	0.857712	0.246972	0.532208Oregon	0.812756	1.260538	0.818304        b	d	eUtah	-0.59	-0.35	0.82Ohio	-1.71	0.17	-1.08Texas	0.86	0.25	0.53Oregon	0.81	1.26	0.82

按元素应用某函数必须使用 applymap。取这个名字的原因是 SerIEs 有一个 map 方法就是用来按元素调用函数的。

1 frame['].map(format)
Utah       0.82Ohio      -1.08Texas      0.53Oregon     0.82name: e,dtype: object
排序和排名

对行索引进行排列:

1 obj = pd.SerIEs(range(4),1)">3 obj.sort_index()
d    0a    1b    2c    3dtype: int64a    1b    2c    3d    0dtype: int64

对列索引进行排列:

1 frame = pd.DataFrame(np.arange(8).reshape((2,1)">frame.sort_index()6 frame.sort_index(axis=1)
	d	a	b	cthree	0	1	2	3one	4	5	6	7        d	a	b	cone	4	5	6	7three	0	1	2	3        a	b	c	dthree	1	2	3	0one	5	6	7	4

按降序排列:

1 frame.sort_index(axis=1,ascending=False)
        d	c	b	athree	0	3	2	1one	4	7	6	5

对于 SerIEs 和 DataFrame,如果需要根据值来进行排列,使用 sort_values 方法:

1 obj = pd.SerIEs([4,7,-3,1)">obj.sort_values()3 obj = pd.SerIEs([4,np.nan,1)">4 obj.sort_values()
2   -33    20    41    7dtype: int644   -3.05    2.00    4.02    7.01    NaN3    NaNdtype: float64
1 frame = pd.DataFrame({': [4,1)">': [0,1,1)">3 frame.sort_values(by=4 frame.sort_values(by=['])
	b	a0	4	01	7	12	-3	03	2	1        b	a2	-3	03	2	10	4	01	7	1        b	a2	-3	00	4	03	2	11	7	1

排名(ranking)用于计算出排名值。

1 obj = pd.SerIEs([7,-5,4,1)">obj.rank()3 obj.rank(method=first')   不使用平均值的排名方法
0    8.51    1.02    8.53    5.54    3.05    5.56    2.07    5.58    5.5dtype: float640    8.01    1.02    9.03    4.04    3.05    5.06    2.07    6.08    7.0dtype: float64

降序排列,并且按最大值指定名次:

1 obj.rank(ascending=False,1)">')
0    2.01    9.02    2.03    6.04    7.05    6.06    8.07    6.08    6.0dtype: float64

按列进行排名:

': [4.3,1],1)">': [-2,5,8,-2.53 frame.rank(axis=1)
        b	a	c0	4.3	0	-2.01	7.0	1	5.02	-3.0	0	8.03	2.0	1	-2.5        b	a	c0	3.0	2.0	1.01	3.0	1.0	2.02	1.0	2.0	3.03	3.0	2.0	1.0
带有重复标签的索引

SerIEs 的重复索引:

1 obj = pd.SerIEs(range(5),1)">obj.index.is_unique4 obj[5 obj[']
a    0a    1b    2b    3c    4dtype: int64Falsea    0a    1dtype: int644

Pandas 的重复索引:

1 df = pd.DataFrame(np.random.randn(4,1)">df3 df.loc[']
        0	        1	        2a	-0.975030	2.041130	1.022168a	0.321428	2.124496	0.037530b	0.343309	-0.386692	-0.577290b	0.002090	-0.890841	1.759072        0	        1	        2b	0.343309	-0.386692	-0.577290b	0.002090	-0.890841	1.759072
求和与计算描述性统计量

sum 求和:

1 df = pd.DataFrame([[1.4,np.nan],[7.1,-4.52                    [np.nan,[0.75,-1.3]],1)">3                   index=[4                   columns=[df.sum()7 df.sum(axis=18 df.mean(axis=1,skipna=False)   不跳过 NAN
	one	twoa	1.40	NaNb	7.10	-4.5c	NaN	NaNd	0.75	-1.3one    9.25two   -5.80dtype: float64a    1.40b    2.60c    0.00d   -0.55dtype: float64a      NaNb    1.300c      NaNd   -0.275dtype: float64

返回最大值或最小值对应的索引:

df.IDxmax()2 df.IDxmin(axis=1)
one    btwo    ddtype: objecta    oneb    twoc    NaNd    twodtype: object

累加:

1 df.cumsum()
	one	twoa	1.40	NaNb	8.50	-4.5c	NaN	NaNd	9.25	-5.8

describe 方法生成一些统计信息:

1 df.describe()
        one	        twocount	3.000000	2.000000mean	3.083333	-2.900000std	3.493685	2.262742min	0.750000	-4.50000025%	1.075000	-3.70000050%	1.400000	-2.90000075%	4.250000	-2.100000max	7.100000	-1.300000
 非数值数据2 obj = pd.SerIEs(['] * 44 obj.describe()
0     a1     a2     b3     c4     a5     a6     b7     c8     a9     a10    b11    c12    a13    a14    b15    cdtype: objectcount     16unique     3top        afreq       8dtype: object

一些常用的统计方法:

countdescribemin,maxargmin,argmaxIDxmin,IDxmaxquantilesummeanmedianmadprodvarstdskewkurtcumsumcummin,cummaxcumproddiffpct_change自相关和协方差

首先安装一个读取数据集的模块:

pip install pandas-datareader -i https://pypi.douban.com/simple

下载一个股票行情的数据集:

import pandas_datareader.data as web2 all_data = {ticker: web.get_data_yahoo(ticker)3             for ticker in [AAPLIBMMSFTGOOG]}4 price = pd.DataFrame({ticker: data[Adj Close]                     5                       for ticker,data  all_data.items()})6 volume = pd.DataFrame({ticker: data[Volume]                      7                        in all_data.items()})

计算价格的百分比变化:

1 returns = price.pct_change()2 returns.tail()
                AAPL	        IBM	        MSFT	        GOOGDate				2019-08-06	0.018930	-0.000213	0.018758	0.0153002019-08-07	0.010355	-0.011511	0.004380	0.0034532019-08-08	0.022056	0.018983	0.026685	0.0262442019-08-09	-0.008240	-0.028337	-0.008496	-0.0139362019-08-12	-0.002537	-0.014765	-0.013942	-0.011195

SerIEs 的 corr 方法会计算两个 SerIEs 的相关性,而 cov 方法计算协方差。

1 returns['].corr(returns[2 returns.MSFT.cov(returns['])
0.488639901663045948.714318020797283e-05

DataFrame 的 corr 方法和 cov 会计算相关性和协方差的矩阵:

returns.corr()2 returns.cov()
	AAPL	        IBM	        MSFT	        GOOGAAPL	1.000000	0.381659	0.453727	0.459663IBM	0.381659	1.000000	0.488640	0.402751MSFT	0.453727	0.488640	1.000000	0.535898GOOG	0.459663	0.402751	0.535898	1.000000        AAPL	        IBM	        MSFT	        GOOGAAPL	0.000266	0.000077	0.000107	0.000117IBM	0.000077	0.000152	0.000087	0.000077MSFT	0.000107	0.000087	0.000209	0.000120GOOG	0.000117	0.000077	0.000120	0.000242

DataFrame 的 corrwith 方法可以计算和其他 SerIEs 或 DataFrame 的相关性:

returns.corrwith(returns.IBM)2 returns.corrwith(volume)
AAPL    0.381659IBM     1.000000MSFT    0.488640GOOG    0.402751dtype: float64AAPL   -0.061924IBM    -0.151708MSFT   -0.089946GOOG   -0.018591dtype: float64
唯一值、值的计数、关系

unique 方法唯一值数组:

1 obj = pd.SerIEs([2 obj.unique()
array(['c','d','b'],dtype=object)

value_counts 方法返回值的计数:

obj.value_counts()2 pd.value_counts(obj.values,sort=False)   等价的写法
a    3c    3b    2d    1dtype: int64c    3b    2d    1a    3dtype: int64

isin 检查 SerIEs 中的数是否属于某个集合:

2 mask = obj.isin([mask4 obj[mask]
0    c1    a2    d3    a4    a5    b6    b7    c8    cdtype: object0     True1    False2    False3    False4    False5     True6     True7     True8     Truedtype: bool0    c5    b6    b7    c8    cdtype: object

get_indexer 将唯一值转换为索引(对于标签转换为数值很管用):

1 to_match = pd.SerIEs([2 unique_vals = pd.SerIEs([3 pd.Index(unique_vals).get_indexer(to_match)
array([0,2])

计算多个列的直方图:

1 data = pd.DataFrame({Qu12                      Qu2': [2,1)">3                      Qu35 data.apply(pd.value_counts).fillna(0)
        Qu1	Qu2	Qu30	1	2	11	3	3	52	4	1	23	3	2	44	4	3	4        Qu1	Qu2	Qu31	1.0	1.0	1.02	0.0	2.0	1.03	2.0	2.0	0.04	2.0	0.0	2.05	0.0	0.0	1.0

 

参考《Python for Data Analysis,2nd Edition》by Wes McKinney

 

总结

以上是内存溢出为你收集整理的Pandas快速上手(一):基本 *** 作 NumPy基本 *** 作快速熟悉全部内容,希望文章能够帮你解决Pandas快速上手(一):基本 *** 作 NumPy基本 *** 作快速熟悉所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1189701.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存