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

发布于:2024-05-02 ⋅ 阅读:(169) ⋅ 点赞:(0)


前言

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

网站公告

今日签到

点亮在社区的每一天
去签到