数据分析工具Pandas(2):Pandas的索引操作

简介: 数据分析工具Pandas(2):Pandas的索引操作

数据分析工具Pandas(1):Pandas的数据结构

数据分析工具Pandas(2):Pandas的索引操作

Pandas的索引操作

索引对象Index

1. Series和DataFrame中的索引都是Index对象

print(type(ser_obj.index))
print(type(df_obj2.index))
print(df_obj2.index)

运行结果:

<class 'pandas.indexes.range.RangeIndex'>
<class 'pandas.indexes.numeric.Int64Index'>
Int64Index([0, 1, 2, 3], dtype='int64')

2. 索引对象不可变,保证了数据的安全

# 索引对象不可变
df_obj2.index[0] = 2

运行结果:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-23-7f40a356d7d1> in <module>()
      1 # 索引对象不可变
----> 2 df_obj2.index[0] = 2
/Users/Power/anaconda/lib/python3.6/site-packages/pandas/indexes/base.py in __setitem__(self, key, value)
   1402 
   1403     def __setitem__(self, key, value):
-> 1404         raise TypeError("Index does not support mutable operations")
   1405 
   1406     def __getitem__(self, key):
TypeError: Index does not support mutable operations

常见的Index种类

  • Index,索引
  • Int64Index,整数索引
  • MultiIndex,层级索引
  • DatetimeIndex,时间戳类型

Series索引

1. index 指定行索引名

 

ser_obj = pd.Series(range(5), index = ['a', 'b', 'c', 'd', 'e'])
print(ser_obj.head())

运行结果:

a    0
b    1
c    2
d    3
e    4
dtype: int64

2. 行索引

ser_obj[‘label’], ser_obj[pos]

# 行索引
print(ser_obj['b'])
print(ser_obj[2])

运行结果:

1
2

3. 切片索引

ser_obj[2:4], ser_obj[‘label1’: ’label3’]

注意,按索引名切片操作时,是包含终止索引的。

 

# 切片索引
print(ser_obj[1:3])
print(ser_obj['b':'d'])

运行结果:

b    1
c    2
dtype: int64
b    1
c    2
d    3
dtype: int64

4. 不连续索引

ser_obj[[‘label1’, ’label2’, ‘label3’]]

# 不连续索引
print(ser_obj[[0, 2, 4]])
print(ser_obj[['a', 'e']])

运行结果:

a    0
c    2
e    4
dtype: int64
a    0
e    4
dtype: int64

5. 布尔索引

# 布尔索引
ser_bool = ser_obj > 2
print(ser_bool)
print(ser_obj[ser_bool])
print(ser_obj[ser_obj > 2])

运行结果:

a    False
b    False
c    False
d     True
e     True
dtype: bool
d    3
e    4
dtype: int64
d    3
e    4
dtype: int64

DataFrame索引

1. columns 指定列索引名

import numpy as np
df_obj = pd.DataFrame(np.random.randn(5,4), columns = ['a', 'b', 'c', 'd'])
print(df_obj.head())

运行结果:

          a         b         c         d
0 -0.241678  0.621589  0.843546 -0.383105
1 -0.526918 -0.485325  1.124420 -0.653144
2 -1.074163  0.939324 -0.309822 -0.209149
3 -0.716816  1.844654 -2.123637 -1.323484
4  0.368212 -0.910324  0.064703  0.486016


image.png

2. 列索引

df_obj[[‘label’]]

# 列索引
print(df_obj['a']) # 返回Series类型
print(df_obj[[0]]) # 返回DataFrame类型
print(type(df_obj[[0]])) # 返回DataFrame类型

3. 不连续索引

df_obj[[‘label1’, ‘label2’]]3. 不连续索引

df_obj[[‘label1’, ‘label2’]]

# 不连续索引
print(df_obj[['a','c']])
print(df_obj[[1, 3]])# 不连续索引
print(df_obj[['a','c']])
print(df_obj[[1, 3]])

运行结果:

          a         c
0 -0.241678  0.843546
1 -0.526918  1.124420
2 -1.074163 -0.309822
3 -0.716816 -2.123637
4  0.368212  0.064703
          b         d
0  0.621589 -0.383105
1 -0.485325 -0.653144
2  0.939324 -0.209149
3  1.844654 -1.323484
4 -0.910324  0.486016

高级索引:标签、位置和混合

Pandas的高级索引有3种

1. loc 标签索引

DataFrame 不能直接切片,可以通过loc来做切片

loc是基于标签名的索引,也就是我们自定义的索引名

# 标签索引 loc
# Series
print(ser_obj['b':'d'])
print(ser_obj.loc['b':'d'])
# DataFrame
print(df_obj['a'])
# 第一个参数索引行,第二个参数是列
print(df_obj.loc[0:2, 'a'])

运行结果:

b    1
c    2
d    3
dtype: int64
b    1
c    2
d    3
dtype: int64
0   -0.241678
1   -0.526918
2   -1.074163
3   -0.716816
4    0.368212
Name: a, dtype: float64
0   -0.241678
1   -0.526918
2   -1.074163
Name: a, dtype: float64

2. iloc 位置索引

作用和loc一样,不过是基于索引编号来索引

# 整型位置索引 iloc
# Series
print(ser_obj[1:3])
print(ser_obj.iloc[1:3])
# DataFrame
print(df_obj.iloc[0:2, 0]) # 注意和df_obj.loc[0:2, 'a']的区别

运行结果:

b    1
c    2
dtype: int64
b    1
c    2
dtype: int64
0   -0.241678
1   -0.526918
Name: a, dtype: float64

3. ix 标签与位置混合索引

ix是以上二者的综合,既可以使用索引编号,又可以使用自定义索引,要视情况不同来使用,

如果索引既有数字又有英文,那么这种方式是不建议使用的,容易导致定位的混乱。

示例代码:

# 混合索引 ix
# Series
print(ser_obj.ix[1:3])
print(ser_obj.ix['b':'c'])
# DataFrame
print(df_obj.loc[0:2, 'a'])
print(df_obj.ix[0:2, 0])

运行结果:

b    1
c    2
dtype: int64
b    1
c    2
dtype: int64
0   -0.241678
1   -0.526918
2   -1.074163
Name: a, dtype: float64b    1
c    2
dtype: int64
b    1
c    2
dtype: int64
0   -0.241678
1   -0.526918
2   -1.074163
Name: a, dtype: float64

注意

DataFrame索引操作,可将其看作ndarray的索引操作

标签的切片索引是包含末尾位置的注意

DataFrame索引操作,可将其看作ndarray的索引操作

标签的切片索引是包含末尾位置的

目录
相关文章
|
8天前
|
数据采集 SQL 数据挖掘
Python数据分析中的Pandas库应用指南
在数据科学和分析领域,Python语言已经成为了一种非常流行的工具。本文将介绍Python中的Pandas库,该库提供了强大的数据结构和数据分析工具,使得数据处理变得更加简单高效。通过详细的示例和应用指南,读者将了解到如何使用Pandas库进行数据加载、清洗、转换和分析,从而提升数据处理的效率和准确性。
|
8天前
|
数据可视化 数据挖掘 C++
数据分析综合案例讲解,一文搞懂Numpy,pandas,matplotlib,seaborn技巧方法
数据分析综合案例讲解,一文搞懂Numpy,pandas,matplotlib,seaborn技巧方法
|
9天前
|
算法 数据挖掘 数据处理
数据分析Pandas之Series,快速上手
数据分析Pandas之Series,快速上手
|
9天前
|
数据采集 机器学习/深度学习 数据可视化
Pandas在数据分析中有广泛的应用场景
Pandas是数据分析利器,适用于数据清洗(处理缺失值、重复项、异常值)、探索分析(统计量、图表)、预处理(特征提取、编码、选择)、建模(线性回归、聚类等)及可视化,与Matplotlib等库配合提升效率。
7 1
|
9天前
|
数据处理 Python
Pandas在数据分析中的应用案例
使用Pandas分析销售数据,通过`read_csv`读取CSV,`groupby`按产品类别分组并应用`agg`计算类别总销售额、平均价和销售量。之后,利用`sort_values`按销售额降序排列,`head`获取前5高销售额类别。示例代码展示了Pandas在数据处理和分析中的高效性。
21 0
|
13天前
|
数据采集 数据可视化 数据挖掘
R语言与Python:比较两种数据分析工具
【4月更文挑战第25天】R语言和Python是目前最流行的两种数据分析工具。本文将对这两种工具进行比较,包括它们的历史、特点、应用场景、社区支持、学习资源、性能等方面,以帮助读者更好地了解和选择适合自己的数据分析工具。
|
19天前
|
数据采集 数据挖掘 数据处理
《Pandas 简易速速上手小册》第8章:Pandas 高级数据分析技巧(2024 最新版)
《Pandas 简易速速上手小册》第8章:Pandas 高级数据分析技巧(2024 最新版)
25 1
|
19天前
|
索引 Python
如何使用Python的Pandas库进行数据透视表(pivot table)操作?
使用Pandas在Python中创建数据透视表的步骤包括:安装Pandas库,导入它,创建或读取数据(如DataFrame),使用`pd.pivot_table()`指定数据框、行索引、列索引和值,计算聚合函数(如平均分),并可打印或保存结果到文件。这允许对数据进行高效汇总和分析。
10 2
|
19天前
|
机器学习/深度学习 数据挖掘 计算机视觉
python数据分析工具SciPy
【4月更文挑战第15天】SciPy是Python的开源库,用于数学、科学和工程计算,基于NumPy扩展了优化、线性代数、积分、插值、特殊函数、信号处理、图像处理和常微分方程求解等功能。它包含优化、线性代数、积分、信号和图像处理等多个模块。通过SciPy,可以方便地执行各种科学计算任务。例如,计算高斯分布的PDF,需要结合NumPy使用。要安装SciPy,可以使用`pip install scipy`命令。这个库极大地丰富了Python在科学计算领域的应用。
13 1
|
20天前
|
数据可视化 数据挖掘 Python
Python中数据分析工具Matplotlib
【4月更文挑战第14天】Matplotlib是Python的数据可视化库,能生成多种图表,如折线图、柱状图等。以下是一个绘制简单折线图的代码示例: ```python import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] plt.figure() plt.plot(x, y) plt.title(&#39;简单折线图&#39;) plt.xlabel(&#39;X轴&#39;) plt.ylabel(&#39;Y轴&#39;) plt.show() ```
13 1