pandas之——Series常用总结

pandas

一 、series

1.1 series的创建

1.1.1 方法一

import numpy as np
import pandas as pd
arr = np.array([88,43,65,87])
ser1 = pd.Series(arr,index=['chinese','math','english','history'])
ser1
chinese    88
math       43
english    65
history    87
dtype: int64
  • 修改索引
ser1.index = ['语文','数学','英语','历史']
ser1
语文    88
数学    43
英语    65
历史    87
dtype: int64

方法二

ser2 = pd.Series({'语文':99,'数学':88,'英语':77,'历史':89})
ser2
语文    99
数学    88
英语    77
历史    89
dtype: int64

1.2 Serise的索引及切片

1.2.1 显式索引

  • 取单个索引的值
ser1
语文    88
数学    43
英语    65
历史    87
dtype: int64
ser1.loc[['语文']]
语文    88
dtype: int64
  • 取多个索引的值
ser1
语文    88
数学    43
英语    65
历史    87
dtype: int64
ser1.loc[['语文','数学']]
语文    88
数学    43
dtype: int64

1.2.2 隐式索引

  • 取单个索引的值
ser1
语文    88
数学    43
英语    65
历史    87
dtype: int64
ser1.iloc[[0]]
语文    88
dtype: int64
  • 取多个索引的值
ser1
语文    88
数学    43
英语    65
历史    87
dtype: int64
ser1.iloc[[0,1]]
语文    88
数学    43
dtype: int64

1.2.3 切片

ser1
语文    88
数学    43
英语    65
历史    87
dtype: int64
方法一
ser1.loc['语文':'英语']    # 左闭右闭
语文    88
数学    43
英语    65
dtype: int64
方法二
ser1.iloc[0:3]    # 左闭右开
语文    88
数学    43
英语    65
dtype: int64

1.2.4 多重索引

  • 多重索引的Series创建与取值
ser2 = pd.Series(data=[78,98,65,87],index=[['leon','leon','jack','jack'],['期中','期末','期中','期末']])
ser2
leon  期中    78
      期末    98
jack  期中    65
      期末    87
dtype: int64
ser2['leon']['期中']
78
  • Series 多重索引切片
ser2
leon  期中    78
      期末    98
jack  期中    65
      期末    87
dtype: int64
ser2.iloc[0:3]
leon  期中    78
      期末    98
jack  期中    65
dtype: int64

1.3 Series的常用方法和操作

ser1
语文    88
数学    43
英语    65
历史    87
dtype: int64
ser1.shape
(4,)
ser1.index
Index(['语文', '数学', '英语', '历史'], dtype='object')
ser1.size
4
ser1.values
array([88, 43, 65, 87])

1.4 Series 的运算

4.1.1 直接相加

ser3 = pd.Series({'a':1,'b':2,'c':3})
ser3
a    1
b    2
c    3
dtype: int64
ser3+50
a    51
b    52
c    53
dtype: int64

4.1.2 add函数

ser3.add(100)
a    101
b    102
c    103
dtype: int64

4.1.3 两个或多个Series之间的运算(在运算中自动对齐不同索引的数据,如果索引不对应,则补NaN)

ser4 = pd.Series({'d':4,'e':5,'f':9})
ser4
d    4
e    5
f    9
dtype: int64
ser5 = ser3.add(ser4,fill_value=1)
ser5
a     2.0
b     3.0
c     4.0
d     5.0
e     6.0
f    10.0
dtype: float64

猜你喜欢

转载自www.cnblogs.com/lpdeboke/p/12800885.html