#-*- coding: utf-8 -*-
'''
作者:时亚东
功能:pandas应用
版本:
时间:2019-10-01
'''
#模块导入
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
'''Serise数据类型——一维数据'''
a = pd.Series([1, 0.3, np.nan])
b = pd.Series(np.array([1, 2, 3]))
print('a\n',a)
print('b\n',b)
# 修改index
a = pd.Series([1, 0.3, np.nan], index = ['a','b','c'])
print(a)
'''DataFrame数据类型——二维数据'''
# date_range()随机产生时间序列
date = pd.date_range('20191001', periods = 5)
#print(date)
# 使用numpy对象创建
df = pd.DataFrame(np.random.randn(5, 4), index = date, columns = list('ABCD'))
# print(df)
# 查看数据
print(df.head()) # 获取前几行数据,默认返回前5行
print(df.tail()) # 获取后几行数据,默认返回后5行
print(df.index) # 获取索引
# print(list(df.index))
print(df.columns) # 获取栏名
print(df.values) # 获取所有值
print(df.describe()) # 获取描述信息
print(df.T) # 转置
print(df.sort_index(axis = 1, ascending = False)) # 对索引对象进行重新排序
print(df.sort_values(by = 'D')) # 针对某一栏中的元素进行排序
print('*' * 50)
# 选择数据
print(df['A']) # 获取某一栏的全部数据
print(df[1:3]) # 获取索引1:3的行数据
print(df['20191001':'20191004']) # 获取索引值为'20191001':'20191004'的行数据
print('*' * 50)
# loc是定位元素的方法
print(df.loc[date[0]]) # 获取date第一个索引的数据
print(df.loc[:, ['A', 'B']]) # 获取栏名为A、B的全部行数据
print(df.loc['20191002':'20191004', ['A','B']]) # 获取索引值为'20191002':'20191004'范围的A、B栏的数据
print(df.loc['20191002', ['A', 'B']]) # 获取索引值为'20191002'的A、B栏的数据
print('*' * 50)
# 通过布尔值获取数据
print(df[df.A > 0]) # 获取A栏中大于0的数据
print(df[df > 0]) # 获取所有大于0的数据
# 赋值
# print(df)
s1 = pd.Series([1,2,3,4], index = pd.date_range('20191002', periods = 4)) # 生成一个Series类型数据
# print('s1\n',s1)
df['F'] = s1 # 将s1添加到df后面
# rint('df\n', df)
df.at[date[0],'A'] = 0 # 指定表中数据进行替换
# print('df\n', df)
df.loc[:, 'D'] = np.array([5] * len(df)) # 指定某一栏的值进行替换,数组类型
# print('df\n', df)
# 处理NaN值得方式
print(df.dropna(how = 'any')) # 删除所有包含NaN的数据行
print(df.fillna(value = 3)) # 使用默认值填充NaN
print(pd.isnull(df)) # 判断是否包含NaN,返回布尔值