Python数据分析系列(五):python数据结构 — Pandas中的Series使用


前言

Pandas 是基于 NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。其中Series和DataFrame是两种最主要的数据结构,本文主要介绍Series的使用。


一、Series创建与属性

  • 基本特征:
    • 类似一维数组的对象
    • 由数据和索引组成
  • 属性:
    • 索引(index):对应是最左侧那一列。
    • 数据(values):每一个索引的右侧对应一个值。
    • name:Series对象及其索引(index)都有一个name属性。

示例1:

import pandas as pd
aSeries=pd.Series([1,2,'a'])
aSeries
# 输出:
# 0    1
# 1    2
# 2    a
# dtype: object

Series字符串表现形式为:索引在左边,值在右边。

示例2:自定义Series的index。

import pandas as pd
aSeries=pd.Series(['apple','orange','lemon'],index=[1,2,3])
aSeries
# 输出:
# 1     apple
# 2    orange
# 3     lemon
# dtype: object

aSeries.index
# 输出:
# Int64Index([1, 2, 3], dtype='int64')

aSeries.index=[4,5,6] #Series索引可以通过赋值的方式就地修改
aSeries
# 输出:
# 4     apple
# 5    orange
# 6     lemon
# dtype: object

aSeries.values
# 输出:
# array(['apple', 'orange', 'lemon'], dtype=object)

示例3:如果数据被存放在一个python字典中,也可以直接通过这个字典来创建Series。

import numpy as np
data={
   'apple':'8.4','orange':'7','lemon':'4'} 
aSeries=pd.Series(data)
aSeries
# 输出:
# apple     8.4
# orange      7
# lemon       4
# dtype: object

示例4:Series及其索引(index)的name属性

import pandas as pd
aSeries=pd.Series(['apple','orange','lemon'],index=[1,2,3])
aSeries.name="price"
aSeries.index.name="id"
aSeries
# 输出:
# id
# 1     apple
# 2    orange
# 3     lemon
# Name: price, dtype: object

二、Series的索引

示例1:索引单个值

import pandas as pd
aSeries=pd.Series(['apple','orange','lemon'],index=['a','b','c'])
aSeries['a']
# 输出:
# 'apple'

aSeries['c']='peach' #Series索引对应的数据可以通过赋值的方式就地修改
aSeries
# 输出:
# a     apple
# b    orange
# c     peach
# dtype: object

示例2:索引一组值

import pandas as pd
aSeries=pd.Series(['apple','orange','lemon'],index=['a','b','c'])
aSeries[['c','a']]
# 输出:
# c    peach
# a    apple
# dtype: object

示例3:层次化索引

import pandas as pd
aSeries= pd.Series(np.random.randn(10),index

相关推荐

最近更新

  1. TCP协议是安全的吗?

    2024-05-02 06:00:04       14 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-02 06:00:04       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-02 06:00:04       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-02 06:00:04       18 阅读

热门阅读

  1. GPU系列(三):如何管理GPU

    2024-05-02 06:00:04       11 阅读
  2. 历届试题 连号区间数

    2024-05-02 06:00:04       11 阅读
  3. HTML_CSS学习:CSS像素与颜色

    2024-05-02 06:00:04       11 阅读
  4. C++中的指针详解

    2024-05-02 06:00:04       9 阅读
  5. iOS 获取到scrollView停止拖动时候的速度

    2024-05-02 06:00:04       9 阅读
  6. Linux内核常用调优参数

    2024-05-02 06:00:04       7 阅读
  7. 移动应用开发:Android vs iOS平台的选择与挑战

    2024-05-02 06:00:04       6 阅读
  8. 【C++之二叉搜索树】

    2024-05-02 06:00:04       13 阅读
  9. nginx配置tcp长连接实现集群

    2024-05-02 06:00:04       11 阅读
  10. Android UI:动画:视图动画

    2024-05-02 06:00:04       9 阅读