• pandas-01 Series()的几种创建方法


    pandas-01 Series()的几种创建方法

    pandas.Series()的几种创建方法。

    import numpy as np
    import pandas as pd
    
    # 使用一个列表生成一个Series
    s1 = pd.Series([1, 2, 3, 4])
    print(s1)
    '''
    0    1
    1    2
    2    3
    3    4
    dtype: int64
    '''
    # 返回所有的索引
    print(s1.index)
    '''
    RangeIndex(start=0, stop=4, step=1)
    '''
    # 使用数组生成一个Series
    s2  = pd.Series(np.arange(7))
    print(s2)
    '''
    0    0
    1    1
    2    2
    3    3
    4    4
    5    5
    6    6
    dtype: int64
    '''
    
    # 使用一个字典生成Series,其中字典的键,就是索引
    s3 = pd.Series({'1':1, '2':2, '3':3})
    print(s3)
    print(s3.values)
    print(s3.index)
    '''
    1    1
    2    2
    3    3
    dtype: int64
    [1 2 3]
    Index(['1', '2', '3'], dtype='object')
    '''
    
    # 使用列表生成序列,并且指定索引
    s4 = pd.Series([1, 2, 3, 4], index=['A', 'B', 'C', 'D'])
    print(s4)
    '''
    A    1
    B    2
    C    3
    D    4
    dtype: int64
    '''
    
    # 通过索引查找值
    print(s4['A']) # 1
    
    print(s4[s4>2])
    '''
    C    3
    D    4
    dtype: int64
    '''
    
    # 将Series转换为字典
    print(s4.to_dict()) #  {'B': 2, 'D': 4, 'C': 3, 'A': 1}
    
    s5 = pd.Series(s4.to_dict())
    print(s5)
    '''
    A    1
    B    2
    C    3
    D    4
    dtype: int64
    '''
    
    # 为s5指定一个新的索引
    index_1 = ['A', 'B', 'C', 'D', 'E']
    s6 = pd.Series(s5, index=index_1)
    print(s6)
    '''
    A    1.0
    B    2.0
    C    3.0
    D    4.0
    E    NaN
    dtype: float64
    '''
    
    # 判断s6的每一项是否为nan
    print(s6.isnull())
    '''
    A    False
    B    False
    C    False
    D    False
    E     True
    dtype: bool
    '''
    print(s6.notnull())
    '''
    A     True
    B     True
    C     True
    D     True
    E    False
    dtype: bool
    '''
    
    # 为 series 命名
    s6.name = 'demo'
    print(s6)
    '''
    A    1.0
    B    2.0
    C    3.0
    D    4.0
    E    NaN
    Name: demo, dtype: float64
    '''
    
    # 为 索引 命名
    s6.index.name = 'demo index'
    print(s6)
    '''
    demo index
    A    1.0
    B    2.0
    C    3.0
    D    4.0
    E    NaN
    Name: demo, dtype: float64
    '''
    
  • 相关阅读:
    shell学习(11)- seq
    bash快捷键光标移动到行首行尾等
    shell学习(10)- if的使用
    Python 执行 Shell 命令
    查看 jar 包加载顺序
    Linux 中的 sudoers
    Ubuntu 开机启动程序
    指定 Docker 和 K8S 的命令以及用户
    Spark on K8S(Standalone)
    Spark on K8S (Kubernetes Native)
  • 原文地址:https://www.cnblogs.com/wenqiangit/p/11252692.html
Copyright © 2020-2023  润新知