#-*- 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,返回布爾值