pandas数组和numpy数组在使用索引数组过滤数组时的区别

 numpy array 过滤后的数组,索引值从 0 开始.

 pandas Series 过滤后的 Series ,保持原来的索引,原来索引是几,就是几.

什么意思呢,来看个栗子:

import numpy as np
import pandas as pd

# 有两个相同的数组,一个是pd Series 一个是 np array
a = pd.Series([1, 2, 3, 4])
c = np.array([1, 2, 3, 4])

# 通过索引数组来过滤数组
d = a[a>3]
e = c[c>3]

print(d[0])   # 报错 KeyError
print(e[0])   # 3
print(d[2])   # 3
print(e[0])   # 报错 IndexError

可见, 对于 pd Series 来说,1234索引是 key ,而不是 index ,所以过滤后的数组,保留了原来的 key ,  3 的key是 2 ,它过滤后的 key 还是 2 

对于 np array 来说,表现更像普通数组,过滤后的数组还是从 0 开始索引,数据 3 原来在位置 2,过滤后到了位置 0

猜你喜欢

转载自www.cnblogs.com/liulangmao/p/9162062.html