美文网首页
pandas之series的创建

pandas之series的创建

作者: 郭祺迦 | 来源:发表于2018-10-10 12:42 被阅读0次

    Series:

      是一种类似与一维数组的对象,由下面两个部分组成:
      1>:values:一组数据(ndarray类型)
      2>:index:相关的数据索引标签

    1):Series的创建

    两种创建方式:
    (1):由列表或numpy数组创建
      默认索引为0到N-1的整数型索引

    由列表创建:
    s1 = Series([1,2,3])
    s1
    '''
    0    1
    1    2
    2    3
    dtype: int64
    '''
    由numpy数组创建:
    np1 = np.array([1,2,3])
    s2 = Series(np1)
    s2
    '''
    0    1
    1    2
    2    3
    dtype: int32
    '''
    
    以上的两个例子可以看到,Series的创建默认的索引是整数0到N-1;我们也可以在创建的时候,指定索引的名称
    
    指定索引名称创建Series:
    s3 = Series(np1,index=list("ABC"))
    s3
    '''
    A    1
    B    2
    C    3
    dtype: int32
    '''
    或者:
    
    s4 = Series(np1,index=['a','b','c'])
    s4
    '''
    a    1
    b    2
    c    3
    dtype: int32
    '''
    注意:在指定索引的时候,如果索引的个数小于元素的个数或者大于元素的个数是会报错的
    

    下面看一下这些情况在Series创建的时候也是可以的

    1>:创建的时候,索引是名称相同;在通过索引取值的时候,取的是全部的名称相同的值

    s6 = Series(np1,index=list('aaa'))
    s6
    '''
    a    1
    a    2
    a    3
    dtype: int32
    '''
    
    取值:
    s6['a']
    '''
    a    1
    a    2
    a    3
    dtype: int32
    '''
    

    2>:可以通过.index方式来设置索引

    创建:
    s7 = Series(np1)
    s7
    '''
    0    1
    1    2
    2    3
    dtype: int32
    '''
    
    通过index的方式设置索引:
    s7.index = list('abc')
    s7
    '''
    a    1
    b    2
    c    3
    dtype: int32
    '''
    

    3>:在创建的时候已经设置了索引,也可以通过.index的方式重新设置索引名称

    s8 = Series(data=np.random.randint(1,10,size=5),index=list('abcde'))
    s8
    '''
    a    9
    b    4
    c    6
    d    5
    e    7
    dtype: int32
    '''
    s8.index = list('ABCDE')
    s8
    '''
    A    9
    B    4
    C    6
    D    5
    E    7
    dtype: int32
    '''
    

    注意:要想重新给索引设置名称,只能一起设置,不能对某一个索引重新设置

    特别地,由ndarray创建的是引用,而不是副本。对Series元素的改变也会改变原来的ndarray对象中的元素。(列表没有这种情况)

    s9 = Series(data = np.random.randint(0,10,size=8),index=list('abcdefgh'))
    s9
    '''
    a    9
    b    5
    c    6
    d    3
    e    5
    f    1
    g    6
    h    9
    dtype: int32
    '''
    修改某一索引的值,那么这个ndarray也会跟着变化
    
    s9['b'] = 100
    s9
    '''
    a      9
    b    100
    c      6
    d      3
    e      5
    f      1
    g      6
    h      9
    dtype: int32
    '''
    

    2):由字典创建

    s10 = Series(data = {'a':1,'b':2,'c':3})
    s10
    '''
    a    1
    b    2
    c    3
    dtype: int64
    '''
    注意:若是在用字典创建的时候,指定了index,但是index的索引不等于key,返回的是NaN
    
    s10 = Series(data = {'a':1,'b':2,'c':3},index=list('ert'))
    s10
    '''
    e   NaN
    r   NaN
    t   NaN
    dtype: float64
    '''
    
    

    相关文章

      网友评论

          本文标题:pandas之series的创建

          本文链接:https://www.haomeiwen.com/subject/tnkpaftx.html