• Pandas入门——Series基本操作


    Series学习

    使用Python的列表创建Series:

    import numpy as np
    import pandas as pd
    # 使用list创建
    s1 = pd.Series([1,2,3,4]) # 可以发现索引index默认从0开始进行自动索引
    s1
    0    1
    1    2
    2    3
    3    4
    dtype: int64
    
     
    
    # 值属性,可以方便查看Series的值
    s1.values
    array([1, 2, 3, 4], dtype=int64)
    
     
    
    # 索引index属性,返回的是索引从开始到结束和间隔的值
    s1.index 
    RangeIndex(start=0, stop=4, step=1)
    
    
    # 使用numpy的数组进行创建
    s2 = pd.Series(np.arange(10)
    s2
    0    0
    1    1
    2    2
    3    3
    4    4
    5    5
    6    6
    7    7
    8    8
    9    9
    dtype: int32
     
    
    # 通过字典进行创建
    s3 = pd.Series({'1':1, '2':2, '3':3})
    s3
    1    1
    2    2
    3    3
    dtype: int64
     
    s3.values
    array([1, 2, 3], dtype=int64)
    
    s3.index
    Index(['1', '2', '3'], dtype='object')
    
     
    # 手动赋值索引
    s4 = pd.Series([1,2,3,4], index=['A','B','C','D'])
    s4
    A    1
    B    2
    C    3
    D    4
    dtype: int64
    
     
    s4.values
    array([1, 2, 3, 4], dtype=int64)
    
    s4.index
    Index(['A', 'B', 'C', 'D'], dtype='object')
    
    s4['A']  # 根据索引取值
    1
    
    s4[s4>1] # 根据值得范围取值
    B    2
    C    3
    D    4
    dtype: int64
    
     
    s4.to_dict() # 把Series转换为字典输出,也就是说可以通过字典创建Series,也可以通过Series转换为字典
    {'A': 1, 'B': 2, 'C': 3, 'D': 4}
    
     
    s5 = pd.Series(s4.to_dict()) # 来回转
    s5
    A    1
    B    2
    C    3
    D    4
    dtype: int64
    
     
    index_1 = ['A','B','C','D','E'] # 可单独把索引写出,再赋值给Series,同时多增加一个索引
    s6 = pd.Series(s5, index=index_1)
    s6  # 多增加的索引的值为NAN
    A    1.0
    B    2.0
    C    3.0
    D    4.0
    E    NaN
    dtype: float64
    
    
    pd.isnull(s6) # 根据pd.isnall()判断Series的元素是否有空值,如果有返回Ture,反之False
    A    False
    B    False
    C    False
    D    False
    E     True
    dtype: bool
    
     
    pd.notnull(s6) # 类似的操作 
    A     True
    B     True
    C     True
    D     True
    E    False
    dtype: bool
    
     
    s6.name = 'demo' # 给Series赋予名字
    s6
    A    1.0
    B    2.0
    C    3.0
    D    4.0
    E    NaN
    Name: demo, dtype: float64
    
     
    
    s6.index.name = 'demo_index' # 给索引起个名字
    s6
    demo_index
    A    1.0
    B    2.0
    C    3.0
    D    4.0
    E    NaN
    Name: demo, dtype: float64
    
     
    s6.index 
    Index(['A', 'B', 'C', 'D', 'E'], dtype='object', name='demo_index')
    
     
  • 相关阅读:
    实验四: Android程序设计
    实验三 敏捷开发与XP实践-1
    mini dc课堂练习补交
    20155216 2016-2017-2 《Java程序设计》第十周学习总结
    第十二周课上练习
    20155210 潘滢昊 Java第三次实验
    20155210 2016-2017-2 《Java程序设计》第10周学习总结
    20155210 潘滢昊2016-2017-2 《Java程序设计》第9周学习总结
    20155210潘滢昊 Java第二次试验
    20155210潘滢昊 2016-2017-2 《Java程序设计》第8周学习总结
  • 原文地址:https://www.cnblogs.com/chenchang-rjgc/p/12355217.html
Copyright © 2020-2023  润新知