本章内容
- 多层索引
- 时间序列
一、多层索引
1、Series可以创建多层索引:
import numpy as np
import pandas as pd
from pandas import Series,DataFrame
# Series也可以创建多层索引
s = Series(np.random.randint(0,150,size=6),index=list('abcdef'))
print(s)
s = Series(np.random.randint(0,150,size=6),index=[['a','a','b','b','c','c'],['期中','期末','期中','期末','期中','期末']])
print(s)
'''
a 63
b 77
c 113
d 102
e 21
f 109
dtype: int64
a 期中 11
期末 30
b 期中 46
期末 124
c 期中 124
期末 35
dtype: int64
'''
2、DataFrame创建多层索引:
df1 = DataFrame(np.random.randint(0,150,size=(6,4)),
columns = ['zs','ls','ww','zl'],
index = [['python','python','math','math','En','En'],['期中','期末','期中','期末','期中','期末']])
print(df1)
'''
zs ls ww zl
python 期中 7 122 69 4
期末 96 49 149 18
math 期中 105 69 128 63
期末 145 83 89 65
En 期中 46 69 144 127
期末 148 136 76 52
'''
3、特定结构from_arrays与from_product
class1=['python','python','math','math','En','En']
class2=['期中','期末','期中','期末','期中','期末']
# 创建索引
m_index2=pd.MultiIndex.from_arrays([class1,class2])
df2=DataFrame(np.random.randint(0,150,(6,4)),index=m_index2)
print(df2)
'''
0 1 2 3
python 期中 89 52 37 93
期末 40 121 0 69
math 期中 139 17 36 39
期末 106 119 96 123
En 期中 130 35 67 113
期末 140 145 0 13
'''
class1=['期中','期中','期中','期末','期末','期末']
class2=['python','math','En','python','math','En']
m_index2=pd.MultiIndex.from_arrays([class1,class2])
df2=DataFrame(np.random.randint(0,150,(6,4)),index=m_index2)
print(df2)
'''
0 1 2 3
期中 python 35 27 119 36
math 25 131 147 83
En 33 62 88 30
期末 python 111 1 99 96
math 45 126 49 111
En 76 27 76 98
'''
class1=['python','math','En']
class2=['期中','期末']
m_index2=pd.MultiIndex.from_product([class1,class2])
df2=DataFrame(np.random.randint(0,150,(6,4)),index=m_index2)
print(df2)
'''
0 1 2 3
python 期中 38 80 3 93
期末 129 113 49 84
math 期中 75 135 38 88
期末 91 48 69 69
En 期中 45 130 52 5
期末 113 26 106 33
'''
4、多层索引对象的索引操作
# series
s = Series(np.random.randint(0,150,size=6),
index=[['a','a','b','b','c','c'],['期中','期末','期中','期末','期中','期末']])
print(s)
# 取一个第一级索引
print(s['a'])
# 取多个第一级索引
print(s[['a','b']])
# 根据索引获取值
print(s['a','期末'])
# loc方法取值
print(s.loc['a'])
print(s.loc[['a','b']])
print(s.loc['a','期末'])
# iloc方法取值(iloc计算的事最内层索引)
print(s.iloc[1])
print(s.iloc[1:4])
'''
a 期中 110
期末 42
b 期中 63
期末 55
c 期中 19
期末 117
dtype: int32
期中 110
期末 42
dtype: int32
a 期中 110
期末 42
b 期中 63
期末 55
dtype: int32
42
'''
# DataFrame
class1=['python','math','En']
class2=['期中','期末']
m_index2=pd.MultiIndex.from_product([class1,class2])
df2=DataFrame(np.random.randint(0,150,(6,4)),index=m_index2)
print(df2)
# 获取列
print(df2[0])
# 一级索引
print(df2.loc['python'])
# 多个一级索引
print(df2.loc[['python','math']])
# 取一行
print(df2.loc['python','期末'])
# 取一值
print(df2.loc['python','期末'][0])
# iloc是只取最内层的索引的
print(df2.iloc[0]) # 第一行
'''
0 1 2 3
python 期中 111 2 58 95
期末 112 11 32 110
math 期中 96 41 97 17
期末 120 44 104 71
En 期中 85 43 46 29
期末 63 97 74 132
python 期中 111
期末 112
math 期中 96
期末 120
En 期中 85
期末 63
Name: 0, dtype: int32
0 1 2 3
期中 111 2 58 95
期末 112 11 32 110
0 1 2 3
python 期中 111 2 58 95
期末 112 11 32 110
math 期中 96 41 97 17
期末 120 44 104 71
0 112
1 11
2 32
3 110
Name: (python, 期末), dtype: int32
112
0 111
1 2
2 58
3 95
Name: (python, 期中), dtype: int32
'''
二、时间序列
时间序列频率:
D 日历日的每天
B 工作日的每天
H 每小时
T或min 每分钟
S 每秒
L或ms 每毫秒
U 每微秒
M 日历日的月底日期
BM 工作日的月底日期
MS 日历日的月初日期
BMS 工作日的月初日期
1、生成一段时间范围
import pandas as pd
import numpy as np
'''
该函数主要用于生成一个固定频率的索引,必须指定start、end、periods中的两个参数值,否则报错
'''
date = pd.date_range(start='20190501',end='20190530')
print(date)
# freq:日期偏移量,取值为string或DateOffset,默认为'D', freq='1h30min' freq='10D'
# periods:固定时期,取值为整数或None
date = pd.date_range(start='20190501',periods=10,freq='10D')
print(date)
'''
DatetimeIndex(['2019-05-01', '2019-05-02', '2019-05-03', '2019-05-04',
'2019-05-05', '2019-05-06', '2019-05-07', '2019-05-08',
'2019-05-09', '2019-05-10', '2019-05-11', '2019-05-12',
'2019-05-13', '2019-05-14', '2019-05-15', '2019-05-16',
'2019-05-17', '2019-05-18', '2019-05-19', '2019-05-20',
'2019-05-21', '2019-05-22', '2019-05-23', '2019-05-24',
'2019-05-25', '2019-05-26', '2019-05-27', '2019-05-28',
'2019-05-29', '2019-05-30'],
dtype='datetime64[ns]', freq='D')
DatetimeIndex(['2019-05-01', '2019-05-11', '2019-05-21', '2019-05-31',
'2019-06-10', '2019-06-20', '2019-06-30', '2019-07-10',
'2019-07-20', '2019-07-30'],
dtype='datetime64[ns]', freq='10D')
'''
2、时间序列在DataFrame中的作用
# 可以将时间作为索引
index = pd.date_range(start='20190101',periods=10)
df = pd.Series(np.random.randint(0,10,size = 10),index=index)
print(df)
'''
2019-01-01 8
2019-01-02 6
2019-01-03 7
2019-01-04 4
2019-01-05 3
2019-01-06 4
2019-01-07 7
2019-01-08 4
2019-01-09 2
2019-01-10 3
Freq: D, dtype: int64
'''
3、获取指定日期数据
long_ts = pd.Series(np.random.randn(1000),index=pd.date_range('1/1/2019',periods=1000))
print(long_ts)
# 根据年份获取
result = long_ts['2020']
print(result)
# 年份和日期获取
result = long_ts['2020-05']
print(result)
# 使用切片
result = long_ts['2020-05-01':'2020-05-06']
print(result)
'''
2019-01-01 -0.237565
2019-01-02 1.186377
2019-01-03 0.083208
2019-01-04 1.197674
2019-01-05 -0.192879
...
2021-09-22 -0.489195
2021-09-23 -0.424459
2021-09-24 -0.884793
2021-09-25 0.616869
2021-09-26 -1.266669
Freq: D, Length: 1000, dtype: float64
2020-01-01 -0.745977
2020-01-02 -0.369469
2020-01-03 -0.204742
2020-01-04 0.376163
2020-01-05 1.647412
...
2020-12-27 -0.978345
2020-12-28 -1.716052
2020-12-29 -0.655194
2020-12-30 0.801930
2020-12-31 -0.955629
Freq: D, Length: 366, dtype: float64
2020-05-01 0.362031
2020-05-02 -1.339570
2020-05-03 1.596600
2020-05-04 -0.418694
2020-05-05 0.648603
2020-05-06 -0.611750
2020-05-07 -0.459537
2020-05-08 -0.779661
2020-05-09 1.708588
2020-05-10 0.975429
2020-05-11 -0.107914
2020-05-12 -1.339984
2020-05-13 -0.647215
2020-05-14 -0.894258
2020-05-15 -1.239079
2020-05-16 1.648267
2020-05-17 -0.178392
2020-05-18 1.844536
2020-05-19 -1.005984
2020-05-20 0.552462
2020-05-21 0.289016
2020-05-22 -0.600272
2020-05-23 -0.083809
2020-05-24 -0.927003
2020-05-25 0.396922
2020-05-26 0.694272
2020-05-27 -0.755551
2020-05-28 -0.787471
2020-05-29 -1.092762
2020-05-30 -0.649857
2020-05-31 -1.655115
Freq: D, dtype: float64
2020-05-01 0.362031
2020-05-02 -1.339570
2020-05-03 1.596600
2020-05-04 -0.418694
2020-05-05 0.648603
2020-05-06 -0.611750
Freq: D, dtype: float64
'''
4、between_time函数
# 通过between_time()返回位于指定时间段的数据集
index=pd.date_range("2018-03-17","2018-03-30",freq="2H")
ts = pd.Series(np.random.randn(157),index=index)
print(ts.between_time("7:00","17:00"))
'''
2018-03-17 08:00:00 1.109485
2018-03-17 10:00:00 -0.155996
2018-03-17 12:00:00 -0.115052
2018-03-17 14:00:00 -0.942430
2018-03-17 16:00:00 0.999180
...
2018-03-29 08:00:00 -0.504113
2018-03-29 10:00:00 0.581727
2018-03-29 12:00:00 -0.162035
2018-03-29 14:00:00 0.295301
2018-03-29 16:00:00 2.182383
Length: 65, dtype: float64
'''
# 这些操作也都适用于dataframe
index=pd.date_range('1/1/2019',periods=100)
df = pd.DataFrame(np.random.randn(100,4),index=index)
print(df.loc['2019-04'])
'''
0 1 2 3
2019-04-01 -1.099824 0.480082 -0.383058 -1.301430
2019-04-02 0.036537 -0.620041 1.017620 0.346523
2019-04-03 -0.767653 0.285558 0.803286 0.521594
2019-04-04 0.429744 0.612181 -1.250233 -0.211316
2019-04-05 0.792158 0.157952 0.285047 -0.297007
2019-04-06 -1.086871 0.684467 -0.273507 -0.588283
2019-04-07 1.049609 -0.011615 1.065160 -0.899949
2019-04-08 -0.602264 -0.819552 1.087355 0.510758
2019-04-09 1.075989 -1.459639 -2.061529 0.091204
2019-04-10 -0.270775 -1.097525 0.271081 0.668827
'''
5、移位日期:
ts = pd.Series(np.random.randn(10),index = pd.date_range('1/1/2019',periods = 10))
print(ts)
'''
2019-01-01 0.891570
2019-01-02 1.467818
2019-01-03 2.263255
2019-01-04 -0.529046
2019-01-05 -0.015847
2019-01-06 1.182142
2019-01-07 -0.451722
2019-01-08 -0.225006
2019-01-09 0.011101
2019-01-10 0.376488
Freq: D, dtype: float64
'''
# 移动数据,索引不变,默认由Nan填充
# periods:移动的位数 负数是向上移动
# fill_value:移动后填充数据
ts1 = ts.shift(periods = 2,fill_value = 100)
print(ts1)
'''
2019-01-01 100.000000
2019-01-02 100.000000
2019-01-03 0.891570
2019-01-04 1.467818
2019-01-05 2.263255
2019-01-06 -0.529046
2019-01-07 -0.015847
2019-01-08 1.182142
2019-01-09 -0.451722
2019-01-10 -0.225006
Freq: D, dtype: float64
'''
# 将索引移动指定的时间
ts2 = ts.tshift(2)
print(ts2)
'''
2019-01-03 0.891570
2019-01-04 1.467818
2019-01-05 2.263255
2019-01-06 -0.529046
2019-01-07 -0.015847
2019-01-08 1.182142
2019-01-09 -0.451722
2019-01-10 -0.225006
2019-01-11 0.011101
2019-01-12 0.376488
Freq: D, dtype: float64
'''
6、时间戳的相互转换:
#将时间戳转化成时间根式
pd. to_datetime(1554970740000,unit='ms')
# utc是协调世界时,时区是以UTC的偏移量的形式表示的,但是注意设置utc=True ,是让pandas对象具有时区性质,对于一列进行转换的,会造成转换错误
# unit='ms' 设置粒度到达毫秒级
pd.to_datetime(1554970740000,unit='ms').tz_1oca1ize('UTC').tz_convert('Asia/Shanghai')
#处理一列
df = pd.DataFrame([1554970740000, 1554970800000, 1554970860000],columns = ['time_stamp'])
pd.to_datetime(df['time_stamp'],unit='ms').dt.tz_1oca1ize('UTC').dt.tz_convert('Asia/Shanghai ')#先赋予标准时区,再转换到东八区
#处理中文
pd.to_datetime('2019年10月10日',format='%Y年%m月%d日') # 2019-10-10 00:00:00
网友评论