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


前言

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

本系列主要使用工具是Jupyter Notebook,要显示数据的全部行和列,运行下面两个语句:

  • pd.options.display.max_columns = None
  • pd.options.display.max_rows = None

一、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=[['a','a','a','b','b','b',
  • 14
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值