pandas基础(1)_Series和DataFrame

1:pandas简介

               Python Data Analysis Library 或 pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具。pandas提供了大量能使我们快速便捷地处理数据的函数和方法。你很快就会发现,它是使Python成为强大而高效的数据分析环境的重要因素之一。

2:Series和DataFrame()

 1:Series:是一种类似于一维数组的对象,由下面两个部分组成:

              Values:一组数据值(ndarray)类型

              Index:相关的数据索引标签、

 2:Series的创建方法

1)由列表和numpy数组创建

>>> s=Series([1,3,4,5])

>>> s

0    1

1    3

2    4

3    5

dtype: int64

>>> #会自动将索引打印出来

>>> s.index=list('abcd')

>>> s

a    1

b    3

c    4

d    5

dtype: int64

>>> #使索引变成了字母abcd

>>> s = Series([1,2,3,4],index=['mike','sana','luna','la'])

>>> s

mike    1

sana    2

luna    3

la      4

dtype: int64

>>> #Series里面的数据是一维的

(2)由字典创建

>>> #Series里面的数据是一维的

>>> s1=Series({'a':1,'b':2})

>>> s1

a    1

b    2

dtype: int64

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

3:Series的索引

(1)显示索引

>>> s=Series(np.random.random(10),index=list('abcdefghig'))

>>> s

a    0.370897

b    0.993346

c    0.148304

d    0.456316

e    0.365877

f    0.424124

g    0.685219

h    0.694954

i    0.563674

g    0.982072

dtype: float64

>>> s['a']#使用index作为索引值

0.37089735452082695

>>> s.loc['a']#使用,loc方法显示获取索引

0.37089735452082695

>>> s[0]

0.37089735452082695

>>> s.loc[0]#因为是显示索引会报错

Traceback (most recent call last):

  File "<pyshell#59>", line 1, in <module>

    s.loc[0]#因为是显示索引会报错

>>> s.iloc[0]

0.37089735452082695

>>> #因为此时是隐式索引所以不会报错,,隐式索引默认为0,1,2.......

>>> s.loc['a':'e']

a    0.370897

b    0.993346

c    0.148304

d    0.456316

e    0.365877

dtype: float64

>>> #切片处理

>>>

Series的基本概念

  可以把Series看成一个定长的有序字典

可以通过shapesizeindexvalues,,等得到series的属性

>>> s.shape

(10L,)

>>> s.size

10

>>> s.index

Index([u'a', u'b', u'c', u'd', u'e', u'f', u'g', u'h', u'i', u'g'], dtype='object')

>>> s.values

array([0.37089735, 0.99334641, 0.14830394, 0.45631575, 0.36587742,

       0.42412389, 0.68521869, 0.69495357, 0.56367448, 0.98207233])

>>> #Seriesvalues,就是一个ndrray包含关系,升级的关系,有了索引更方便

>>> s.shape

(10L,)

>>> s.head

<bound method Series.head of a    0.370897

b    0.993346

c    0.148304

d    0.456316

e    0.365877

f    0.424124

g    0.685219

h    0.694954

i    0.563674

g    0.982072

dtype: float64>

>>> s.tail

<bound method Series.tail of a    0.370897

b    0.993346

c    0.148304

d    0.456316

e    0.365877

f    0.424124

g    0.685219

h    0.694954

i    0.563674

g    0.982072

dtype: float64>

>>> #Series对象本身实例有一个name属性

>>> s.name="列名"

>>> s

a    0.370897

b    0.993346

c    0.148304

d    0.456316

e    0.365877

f    0.424124

g    0.685219

h    0.694954

i    0.563674

g    0.982072

Name: ????, dtype: float64

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、’

4:Series的运算

>>> s.add(10,fill_value=0)#在进行算数运算时,如果包含nan ,那么fill_value默认设置为fill_value

a    10.370897

b    10.993346

c    10.148304

d    10.456316

e    10.365877

f    10.424124

g    10.685219

h    10.694954

i    10.563674

g    10.982072

Name: ????, dtype: float64

>>> #Series之间的运算

>>> s1=Series([2,4,7,9],index=[0,1,2,3])

>>> s2=Series([1,2,3,4],index=[2,3,4,5])

>>> s1+s2#Series索引值,进行相加时,就是索引值进行相加

0     NaN

1     NaN

2     8.0

3    11.0

4     NaN

5     NaN

dtype: float64

>>> #要保留所有的index,必须使用.add()函数

>>> s1.add(s2,fill_value=0)

0     2.0

1     4.0

2     8.0

3    11.0

4     3.0

5     4.0

dtype: float64

>>> s1.add(s2)

0     NaN

1     NaN

2     8.0

3    11.0

4     NaN

5     NaN

dtype: float64

>>> #因为不同的Series存在不同的索引值,所以当对应另一个Series不存在该索引时要把fill_value定义为0

>>> s=Series([1,2,None])

>>> nd=np.array([1,2,None])

>>> s.sum()

3.0

>>> nd.sum()#会报错,因为有非数字,没办法进行计算

Traceback (most recent call last):

  File "<pyshell#89>", line 1, in <module>

    nd.sum()#会报错,因为有非数字

  File "E:\Python\lib\site-packages\numpy\core\_methods.py", line 32, in _sum

    return umr_sum(a, axis, dtype, out, keepdims)

TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

>>> #ndarray中如果有nan,没有办法进行计算,而Series可以

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

5:DataFrame的定义

        DataFrame是一个【表格型】的数据结构,可以看做是【由Series组成的字典】公用一个索引。DataFrame由按一定顺序排列的多列数据。设计初衷是将Series的使用场景从一维扩展到多维,DataFrame既有行索引,也有列索引

行索引:index

列索引:column

值:valuesnumpy的二维数组)

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

6:DataFrame的创建:

  最常用的方法是由一个字典来创建,DataFrame以字典的建作为每一{}的名称。以字典的值作为每一列

此外,dataframeSeries一样会自动为每一行加索引,相应值为nan

>>> df= DataFrame({'height':[175,180,169,188],'age':np.random.randint(18,25,size=4),'sex':['boy','girl','boy','girl']})

>>> df

   age  height   sex

0   22     175   boy

1   20     180  girl

2   22     169   boy

3   20     188  girl

>>> df= DataFrame({'height':[175,180,169,188],'age':np.random.randint(18,25,size=4),'sex':['boy','girl','boy','girl']},index=list('ABCD'),columns=['height','age','sex','weight'])

>>> df

   height  age   sex weight    #weight默认为nan

A     175   19   boy    NaN

B     180   23  girl    NaN

C     169   21   boy    NaN

D     188   18  girl    NaN

>>> df.shape

(4, 4)

>>> df.values

array([[175L, 19, 'boy', nan],

       [180L, 23, 'girl', nan],

       [169L, 21, 'boy', nan],

       [188L, 18, 'girl', nan]], dtype=object)

>>> df.columns

Index([u'height', u'age', u'sex', u'weight'], dtype='object')

>>> df.index

Index([u'A', u'B', u'C', u'D'], dtype='object')

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

7:DataFrame的索引

(1)对列进行索引

        。通过类似字典的方式

        。通过属性的方式

 >>> df['age']

A    19

B    23

C    21

D    18

Name: age, dtype: int32

>>> #检索列返回值是Series

>>>

>>> df.age

A    19

B    23

C    21

D    18

Name: age, dtype: int32

>>> #对于DataFrame,列名,就相当于属性,

>>> #DataFrame是统计数据时,用的表格,某一个事物属性,每个属性对应Dataframe列名

>>> df['A']#该方法无法检索行,会报错

>>> #使用.loc[]index来进行索引

>>> #使用.ix[]来进行索引,(过时)

>>> #使用iloc[]加整数来进行索引

>>> #对于行进行索引,返回值也是Series

>>> df.loc[['A','B']]

   height  age   sex weight

A     175   19   boy    NaN

B     180   23  girl    NaN

>>> #!!!['A','B'],如果检索多行,返回的数据就是DataFrame

>>> df.loc['A':'C']

   height  age   sex weight

A     175   19   boy    NaN

B     180   23  girl    NaN

C     169   21   boy    NaN

>>> #AC左闭右闭

>>> df['height':'age']#对列是不可以进行切片的

Empty DataFrame

Columns: [height, age, sex, weight]

Index: []

>>> df.iloc[1:3]#隐式索引

   height  age   sex weight

B     180   23  girl    NaN

C     169   21   boy    NaN

>>> #左开右闭

#!!!,DataFrame自身有bug,索引是汉字,有时无法检索

>>> df['sex']#直接用中括号时,索引表示的是列索引,切片表示的是行切片

A     boy

B    girl

C     boy

D    girl

Name: sex, dtype: object

>>> df['sex']['A':'B']

A     boy

B    girl

Name: sex, dtype: object

>>> df['sex']['A':'B']=['','']

>>> df

   height  age   sex weight

A     175   19    ??    NaN

B     180   23     ?    NaN

C     169   21   boy    NaN

D     188   18  girl    NaN

>>> df.loc['C','height']

169

>>> #检索行的时候,参数可以是多个

>>> #但是列无法完成该类型的操作

>>> df.values[0,2]

'\xc4\xd0'

>>> '\xc5\xae'#通过坐标进行检索

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

8:DataFrame的计算

de1=DataFrame(np.random.randint(0,150,size=(5,4)),index=['A','B','C','D','E'],columns=['a','b','c','e'])

>>> de1

     a    b    c    e

A  113  143   22   28

B  102  120   80  144

C   37   36  120   80

D  134   82   65   96

E   49   51   46   23

>>> de2=DataFrame(np.random.randint(0,150,size=(4,4)),index=['A','B','C','D'],columns=['a','b','c','e'])

>>> de2

     a   b   c    e

A   35  13  90   11

B   58  63  59   38

C   18  56  49  111

D  142  24  29   33

>>> de2.add(de1)

       a      b      c      e

A  148.0  156.0  112.0   39.0

B  160.0  183.0  139.0  182.0

C   55.0   92.0  169.0  191.0

D  276.0  106.0   94.0  129.0

E    NaN    NaN    NaN    NaN

>>> de2.add(de1,fill_value=0)

       a      b      c      e

A  148.0  156.0  112.0   39.0

B  160.0  183.0  139.0  182.0

C   55.0   92.0  169.0  191.0

D  276.0  106.0   94.0  129.0

E   49.0   51.0   46.0   23.0

>>> #fillvalue=0可以避免出现nan的情况

>>> de1+de2

       a      b      c      e

A  148.0  156.0  112.0   39.0

B  160.0  183.0  139.0  182.0

C   55.0   92.0  169.0  191.0

D  276.0  106.0   94.0  129.0

E    NaN    NaN    NaN    NaN

>>> de1=DataFrame(np.random.randint(0,150,size=(3,3)),index=['A','B','C'],columns=['a','b','c'])

>>> de1

     a    b    c

A  140    4  101

B  120  101  127

C  127   71   91

>>> de2

     a   b   c    e

A   35  13  90   11

B   58  63  59   38

C   18  56  49  111

D  142  24  29   33

>>> de1.add(de2)

       a      b      c   e

A  175.0   17.0  191.0 NaN

B  178.0  164.0  186.0 NaN

C  145.0  127.0  140.0 NaN

D    NaN    NaN    NaN NaN

>>> #无论是行索引还是列索引缺少了都要加NaN

>>> de1['a'].loc['A']=100

>>> de1

     a    b    c

A  100    4  101

B  120  101  127

C  127   71   91

>>> de1['a']

A    100

B    120

C    127

Name: a, dtype: int32

>>> s1=de1['a']

>>> s1+de1

    A   B   C   a   b   c

A NaN NaN NaN NaN NaN NaN

B NaN NaN NaN NaN NaN NaN

C NaN NaN NaN NaN NaN NaN

>>> #s1因为是Series索引是A,B,C,对于de1索引是a,b,c

>>> s2=de1.loc['A']

>>> s2

a    100

b      4

c    101

Name: A, dtype: int32

>>> s2+de1

     a    b    c

A  200    8  202

B  220  105  228

C  227   75  192

>>> #列索引相同所以可以相加

>>> s2.index

Index([u'a', u'b', u'c'], dtype='object')

>>> de1.columns

Index([u'a', u'b', u'c'], dtype='object')

>>>

Python提供的函数:

+                     add()

-                       sub(),或者multily()

*                      mul(),multiply()

/                        truediv(),div(),divide()

//                         floordiv()

%                        mod()

**                         pow()

>>> ss=de1['a']

>>> ss

A    100

B    120

C    127

Name: a, dtype: int32

>>> de1.add(ss)

    A   B   C   a   b   c

A NaN NaN NaN NaN NaN NaN

B NaN NaN NaN NaN NaN NaN

C NaN NaN NaN NaN NaN NaN

>>> de1.add(ss,axis='index')#ss的索引变成a,b,c

     a    b    c

A  200  104  201

B  240  221  247

C  254  198  218

>>> de1.add(ss,axis=0)

     a    b    c

A  200  104  201

B  240  221  247

C  254  198  218

>>> de1.add(ss,axis=1)

    A   B   C   a   b   c

A NaN NaN NaN NaN NaN NaN

B NaN NaN NaN NaN NaN NaN

C NaN NaN NaN NaN NaN NaN

>>> #如果axis是零,则行是索引,所有列都有效

>>> #以列为单位进行操作,对所有列都有效,同理axis=1相反

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

9:DataFrame丢失数据的处理

处理丢失数据

有两种丢失数据 1 none 2 np.nan(NaN)

np.arange(0,10000)

#相同的计算,int运算的时间少于float,更少与object

PandasNoneNaN都被视为np.nan

df = DataFrame({'age':[20,21,23,19,22],'salary':[10000,20000,11001,10101,21000]},index=['a','b','c','d','e'],columns=['age','salary','work'])

>>> df

   age  salary work

a   20   10000  NaN

b   21   20000  NaN

c   23   11001  NaN

d   19   10101  NaN

e   22   21000  NaN

>>> df.work['a':'b']

a    NaN

b    NaN

Name: work, dtype: object

>>> df.work['a':'b']='python'

>>> df

   age  salary    work

a   20   10000  python

b   21   20000  python

c   23   11001     NaN

d   19   10101     NaN

e   22   21000     NaN

>>> >>> df.isnull()

     age  salary   work

a  False   False  False

b  False   False  False

c  False   False   True

d  False   False   True

e  False   False   True

>>> df.notnull()

    age  salary   work

a  True    True   True

b  True    True   True

c  True    True  False

d  True    True  False

e  True    True  False

>>> #根据获得的数据去除数据的空数据

>>> df.dropna()#去除含有空数据的行

   age  salary    work

a   20   10000  python

b   21   20000  python

>>> #默认为行

>>> df.dropna(how='all')#去除全部为nan的行

   age  salary    work

a   20   10000  python

b   21   20000  python

c   23   11001     NaN

d   19   10101     NaN

e   22   21000     NaN

>>> #所有都为null的才删除

>>> df.fillna(value='java')

   age  salary    work

a   20   10000  python

b   21   20000  python

c   23   11001    java

d   19   10101    java

e   22   21000    java

>>> #使空数据修改为value

#backfill,bfill,是向后填充ffill,pad是向前填充

 >>> df

   age  salary    work

a   20   10000  python

b   21   20000  python

c   23   11001     NaN

d   19   10101     NaN

e   22   21000     NaN

>>> df.fillna(method='backfill')#向后填充,实质是后面一行填充前面一行

   age  salary    work

a   20   10000  python

b   21   20000  python

c   23   11001     NaN

d   19   10101     NaN

e   22   21000     NaN

>>> df.fillna(method='ffill')#向前填充

   age  salary    work

a   20   10000  python

b   21   20000  python

c   23   11001  python

d   19   10101  python

e   22   21000  python

>>> df.fillna(method='ffill',inplace=True)#

>>> df

   age  salary    work

a   20   10000  python

b   21   20000  python

c   23   11001  python

d   19   10101  python

e   22   21000  python

>>> obj=pd.Series(['blue','pure','yellow'],index=[0,2,4])

>>> obj

0      blue

2      pure

4    yellow

dtype: object

>>> obj.reindex(range(6),method='bfill')

0      blue

1      pure

2      pure

3    yellow

4    yellow

5       NaN

dtype: object

>>> #这是向后填充

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

3:总结

pandas的Series和DataFrame是构成表结构的两个重要的库,也是学习pandas的基础。

猜你喜欢

转载自www.cnblogs.com/henuliulei/p/9367866.html