pandas基础一 --------属性、缺失数据处理、时间序列

一、DataFrame概念

1、概念
DataFrame数据表是一种2维数据结构。
其中data、index、columns分别为数据、行索引和列索引
2、创建
使用字典创建(行索引由index决定,列索引由字典的键决定)

dict={
    'Province': ['Guangdong', 'Beijing', 'Qinghai', 'Fujian'],
    'pop': [1.3, 2.5, 1.1, 0.7],
    'year': [2018, 2018, 2018, 2018]}
df2=pd.DataFrame(dict,index=[1,2,3,4])
print(df2)

{‘Province’: [‘Guangdong’, ‘Beijing’, ‘Qinghai’, ‘Fujian’], ‘pop’: [1.3, 2.5, 1.1, 0.7], ‘year’: [2018, 2018, 2018, 2018]}
Province pop year
0 Guangdong 1.3 2018
1 Beijing 2.5 2018
2 Qinghai 1.1 2018
3 Fujian 0.7 2018
Province pop year
0 Guangdong 1.3 2018
1 Beijing 2.5 2018
2 Qinghai 1.1 2018
3 Fujian 0.7 2018

二、属性

from pandas import Series,DataFrame
import pandas as pd
import numpy as np
df1=DataFrame(np.random.randint(0,10,(4,4)),index=[1,2,3,4],columns=['a','b','c','d'])
print(df1)
  • #获取行索引
print(df1.index.tolist())
  • #获取数据的类型
print(df1.dtypes)
  • #获取数据的维度
print(df1.ndim)
  • #以二维数据方式返回
print(df1.values)
  • #展示概览***重要,常用***
print(df1.info())
  • #展示数据的前n行,默认是5行
print(df1.head(2))
  • #展示数据的后n行,默认是5行
print(df1.tail(2))
  • #获取DataFrame的列
#因为只有1列,所以返回的类型为Series
print(df1['name'])
#多个列,类型为DataFrame
print(df1['name','age'])
  • 如何添加一列(后面是内部原理)
df.insert(2,'city',['bj','sh','hb','xm'])
#取出列索引,转换为列表
col_name=df2.columns.tolist()
print(col_name)
#在列索引转换的列表内插入一个元素
col_name.insert(2,"city")
print(col_name)
#改变df2的列索引
df2=df2.reindex(columns=col_name)
print(df2)
#给新增的列赋值
df2["city"]=['bj','sh','hb','xm']
print(df2)

三、数据处理(Nan)※※※

3.1、Series,滤除缺失数据 dropna()

from numpy import nan as NaN
import pandas as pd
se=pd.Series([4,NaN,3,NaN])
print(se)
#滤除所有NAN数据
print(se.dropna())
#返回含有布尔值的series
print(se.notnull())
#同上,结果相反
print(se.isnull())
#先判断True or FALSE,然后通过结果选出true的
print(se[se.notnull()])

0 4.0
1 NaN
2 3.0
3 NaN
dtype: float64
分割线
0 4.0
2 3.0
dtype: float64
分割线
0 True
1 False
2 True
3 False
dtype: bool
分割线
0 False
1 True
2 False
3 True
dtype: bool
分割线
0 4.0
2 3.0
dtype: float64

3.2 DataFrame滤除缺失数据/替换缺失数据

import numpy as np
import pandas as pd
from numpy import nan as NaN
df1=pd.DataFrame(np.random.randint(0,10,(5,5)))
print(df1)
df1.iloc[1:4,3]=NaN
df1.iloc[4,:]=NaN
print(df1)
#滤除含nan数据的行
print(df1.dropna())
#滤除全为nan的行
print(df1.dropna(how='all'))
#滤除全nan的列
print(df1.dropna(axis=1,how='all'))
#保留至少有n个非nan数据的行
print(df1.dropna(thresh=4))

3.3填充缺失数据

  • 用常数填充
    fillna传入inplace=True 直接修改原对象
import numpy as np
import pandas as pd
from numpy import nan as NaN
df1=pd.DataFrame(np.random.randint(0,10,(5,5)))
df1.iloc[1:4,3]=NaN
df1.iloc[4,:]=NaN
print(df1)
print(df1.fillna(0))
#传入inplace=True 直接修改原对象
# df1.fillna(0,inplace=True)
# print(df1)
#通过字典填充不同的常数,key为列索引
print(df1.fillna({0:10,1:20,2:30,3:40,4:50}))
  • 平均值填充、只填充一列
    df1.mean()
import numpy as np
import pandas as pd
from numpy import nan as NaN
df1=pd.DataFrame(np.random.randint(0,10,(5,5)))
df1.iloc[1:4,3]=NaN
df1.iloc[4,:]=NaN
print(df1)
print(df1.fillna(df1.mean()))
#只填充一列
print(df1.iloc[:,1].fillna(df1.iloc[:,1].mean(),inplace=True))
print(df1)
  • 利用前后数据填充
    ffill,bfill
import numpy as np
import pandas as pd
from numpy import nan as NaN
df1=pd.DataFrame(np.random.randint(0,10,(5,5)))
df1.iloc[1:4,3]=NaN
df1.iloc[4,:]=NaN
print(df1)
#填充nan前面的数据,limit限制填充的行数
print(df1.fillna(method='ffill',limit=1))
#填充nan后面的数据,若后面无数据,依旧是nan
print(df1.fillna(method='bfill',limit=1))

3.4删除重复数据

df1=pd.DataFrame({'A':[1,1,1,2,2,3,1],'B':list('aabbbca')})
print(df1)
#判断是否重复,结果为bool,True为重复
print(df1.duplicated())

A B
0 1 a
1 1 a
2 1 b
3 2 b
4 2 b
5 3 c
6 1 a
0 False
1 True
2 False
3 False
4 True
5 False
6 True
dtype: bool

#删除重复行
print(df1.drop_duplicates())
#按照指定列去除重复行
print(df1.drop_duplicates(['A']))
#保留重复行的最后一行,相当于倒序检查重复项
print(df1.drop_duplicates(['A'],keep='last'))
#改变原对象
df1.drop_duplicates(inplace=True)
print(df1)

A B
0 1 a
2 1 b
3 2 b
5 3 c
分割线
A B
0 1 a
3 2 b
5 3 c
分割线
A B
4 2 b
5 3 c
6 1 a
分割线
A B
0 1 a
2 1 b
3 2 b
5 3 c

四、数据合并join

左连接,右连接,一般行合并

df1=pd.DataFrame({'A':[1,1,1,2,2,3,1],'B':list('aabbbca')})
df2=pd.DataFrame({'C':[4,5,6,7,8,9],'D':list('ssdser')})
print(df1)
print(df2)
print(df1.join(df2,how='left'))
print(df1.join(df2,how='right'))
print(df1.join(df2,how='outer'))
#连接多个
print(df1.join([df2,df3]))

五、多层索引

py、c叫做外层
使用product构造

class1=['py','C','go']
class2=['期中','期末']
m_index2=pd.MultiIndex.from_product([class1,class2])
df2=DataFrame(np.random.randint(0,150,(6,4)),index=m_index2)
print(df2)

在这里插入图片描述

多层索引的使用loc是取外层索引,iloc是取内层索引

五、※※※时间序列※※※

5.1生成一段时间范围

date_range(start=’’,end=’’),必须有start/end/periods中至少2个,否则报错
periods:固定时期,整数或无.即往下取n个数据
freq:日期偏移量,默认D。类似步长
closed:left带起始值不带结束值,right带结束值,不带起始值

D日历日的每天
B工作日的每天
H每小时
T/min每分钟
S每秒
M日历日的月底日期
BM工作日的月底日期
MS日历日的月初日期
BMS日历日的月初日期
date=pd.date_range(start='2019-3-1',end='2019-4-1',closed='left')
print(date)

DatetimeIndex([‘2019-03-01’, ‘2019-03-02’, ‘2019-03-03’, ‘2019-03-04’,
‘2019-03-05’, ‘2019-03-06’, ‘2019-03-07’, ‘2019-03-08’,
‘2019-03-09’, ‘2019-03-10’, ‘2019-03-11’, ‘2019-03-12’,
‘2019-03-13’, ‘2019-03-14’, ‘2019-03-15’, ‘2019-03-16’,
‘2019-03-17’, ‘2019-03-18’, ‘2019-03-19’, ‘2019-03-20’,
‘2019-03-21’, ‘2019-03-22’, ‘2019-03-23’, ‘2019-03-24’,
‘2019-03-25’, ‘2019-03-26’, ‘2019-03-27’, ‘2019-03-28’,
‘2019-03-29’, ‘2019-03-30’, ‘2019-03-31’],
dtype=‘datetime64[ns]’, freq=‘D’)

date=pd.date_range(start='2019-3-1',periods=10,freq='2H')
print(date)

DatetimeIndex([‘2019-03-01 00:00:00’, ‘2019-03-01 02:00:00’,
‘2019-03-01 04:00:00’, ‘2019-03-01 06:00:00’,
‘2019-03-01 08:00:00’, ‘2019-03-01 10:00:00’,
‘2019-03-01 12:00:00’, ‘2019-03-01 14:00:00’,
‘2019-03-01 16:00:00’, ‘2019-03-01 18:00:00’],
dtype=‘datetime64[ns]’, freq=‘2H’)

5.2 时间序列在DataFrame中做时间索引

index=pd.date_range(start='2019-3-1',periods=4)
se1=pd.Series(np.random.randint(0,10,4),index=index)
print(se1)

2019-03-01 7
2019-03-02 5
2019-03-03 7
2019-03-04 0
Freq: D, dtype: int32

  • 二维
index = pd.date_range('1/1/2019',periods=20)
df1=pd.DataFrame(np.randmon.randn(20,4),index=index)
print(df1)

5.3过滤目标日期前后的数据 truncate

df.truncate(after=‘2019-1-1’) 将2019-1-1之后的日期的数据滤除

index=pd.date_range(start='2019-3-1',periods=4)
se1=pd.Series(np.random.randint(0,10,4),index=index)
print(se1)
af=se1.truncate(after='2019-3-3')
print(af)

5.4 获取指定年/月/时段的数据 切片

  • 切片
index=pd.date_range(start='2019-3-1',periods=6)
se1=pd.Series(np.random.randint(0,10,6),index=index)
print(se1)
print(se1['2019-3-2':'2019-3-5'])

2019-03-01 2
2019-03-02 9
2019-03-03 6
2019-03-04 4
2019-03-05 4
2019-03-06 0
Freq: D, dtype: int32
2019-03-02 9
2019-03-03 6
2019-03-04 4
2019-03-05 4
Freq: D, dtype: int32

  • between_time() 指定区间的数据
index=pd.date_range(start='2019-3-1',periods=6,freq='2H')
se1=pd.Series(np.random.randint(0,10,6),index=index)
print(se1)
print(se1.between_time('2:00','6:00'))

2019-03-01 00:00:00 3
2019-03-01 02:00:00 7
2019-03-01 04:00:00 9
2019-03-01 06:00:00 7
2019-03-01 08:00:00 2
2019-03-01 10:00:00 9
Freq: 2H, dtype: int32
2019-03-01 02:00:00 7
2019-03-01 04:00:00 9
2019-03-01 06:00:00 7
Freq: 2H, dtype: int32

5.5 移位日期

df1.shift(periods=2) 下移2位数据。 负数时上移
df1.tshift(2) 时间后延2天

df1=pd.Series(np.random.randn(3),index=pd.date_range('2019-3-1',periods=3))
print(df1)
print(df1.shift(periods=2))
df1.tshift(2)

2019-03-01 -0.185816
2019-03-02 0.143093
2019-03-03 1.192123
Freq: D, dtype: float64
2019-03-01 NaN
2019-03-02 NaN
2019-03-03 -0.185816
Freq: D, dtype: float64
2019-03-03 -0.185816
2019-03-04 0.143093
2019-03-05 1.192123
Freq: D, dtype: float64

5.6 时间戳

UTC协调世界时,时区以UTC的偏移量的形式表示

import pytz
print(pytz.common_timezones)

在这里插入图片描述

  • 将时间戳转换为时间格式
pd.to_datetime(1554970740000,unit='ms').tz_localize('UTC').tz_convert('Asia/Shanghai')

Timestamp(‘2019-04-11 16:19:00+0800’, tz=‘Asia/Shanghai’)

df=pd.DataFrame([1554738274756,1558573759473,1559365737462],columns=['time_stamp'])
print(df)
pd.to_datetime(df['time_stamp'],unit='ms').dt.tz_localize('UTC').dt.tz_convert('Asia/Shanghai')

time_stamp
0 1554738274756
1 1558573759473
2 1559365737462
0 2019-04-08 23:44:34.756000+08:00
1 2019-05-23 09:09:19.473000+08:00
2 2019-06-01 13:08:57.462000+08:00
Name: time_stamp, dtype: datetime64[ns, Asia/Shanghai]

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值