Pandas-数据结构-Series(二):Series的索引【下标索引、标签索引、切片索引、布尔型索引】

位置下标,类似序列

import numpy as np
import pandas as pd

s = pd.Series(np.random.rand(5))
print('s = \n', s)
print('\ns[0] = {0}, type(s[0]) = {1}, s[0].dtype = {2}'.format(s[0], type(s[0]), s[0].dtype))
print('\nfloat(s[0]) = {0}, type(float(s[0]) = {1})'.format(float(s[0]), type(float(s[0]))))

打印结果:

s =
0    0.221458
1    0.430786
2    0.096305
3    0.262580
4    0.993637
dtype: float64

s[0] = 0.22145841095529073, type(s[0]) = <class 'numpy.float64'>, s[0].dtype = float64

float(s[0]) = 0.22145841095529073, type(float(s[0]) = <class 'float'>)

Process finished with exit code 0

方法类似下标索引,用[]表示,内写上index,注意index是字符串

  • 如果需要选择多个标签的值,用[[]]来表示(相当于[]中包含一个列表)
  • 多标签索引结果是新的数组
import numpy as np
import pandas as pd

s = pd.Series(np.random.rand(5), index=['a', 'b', 'c', 'd', 'e'])
print('\ns = \n{0}, \n\ntype(s) = {1}'.format(s, type(s)))

print("\ns['a'] = {0}, type(s['a']) = {1}, s['a'].dtype = {2}".format(s['a'], type(s['a']), s['a'].dtype))

print('-' * 100)

sci = s[['a', 'b', 'e']]
print('\nsci = \n{0}, \n\ntype(sci) = {1}'.format(sci, type(sci)))

打印结果:

s =
a    0.648198
b    0.356047
c    0.375873
d    0.811611
e    0.070581
dtype: float64,

type(s) = <class 'pandas.core.series.Series'>

s['a'] = 0.6481978904955534, type(s['a']) = <class 'numpy.float64'>, s['a'].dtype = float64
s1[1:4] =
1    0.223454
2    0.591863
3    0.911600
dtype: float64
s2 =
a    0.398821
b    0.856505
c    0.795255
d    0.985476
e    0.724451
dtype: float64
s2['c'] =
 0.7952552440685834
s2[3] =
 0.9854755359882719
s2[::2] =
a    0.398821
c    0.795255
e    0.724451
dtype: float64
bs1 =
0    False
1     True
2     True
4    False
dtype: bool,
type(bs1) = <class 'pandas.core.series.Series'>,
bs1.dtype = bool
bs3 =
0     True
1     True
2     True
4    False
dtype: bool,
type(bs3) = <class 'pandas.core.series.Series'>, bs3.dtype = bool
s[bs3]
0    11.735721
1    62.482804
2    51.381651
dtype: object

Process finished with exit code 0

Original: https://blog.csdn.net/u013250861/article/details/124002657
Author: u013250861
Title: Pandas-数据结构-Series(二):Series的索引【下标索引、标签索引、切片索引、布尔型索引】

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/677044/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球