pandas筆記(未完成版)

pandas筆記(未完成版)

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt #numpy跟matplotlib經常和pandas配合使用

創建數據

#Series:Series是一種類似於一維數組的對象,由下面兩個部分組成:
#values:一組數據(np(array)類型)
#index:相關的數據索引標籤
s=pd.Series([1,3,5,‘np’,‘nan’,6,8])
print(s)

dates=pd.date_range(‘20190321’,periods=5)#periods 創建總共六個索引
print(dates)

#DataFrame是一個【表格型】的數據結構。DataFrame由按一定順序排列的多列數據組成。設計初衷是將Series的使用場景從一維拓展到多維。DataFrame既有行索引,也有列索引。
#行索引:index
#列索引:columns
#值:values

df=pd.DataFrame(np.random.randn(5,4),index=dates,columns=list(‘ABCD’))#dates屬性當索引,ABCD四個當列
print(df)

print(df.dtypes)#查看不同列的數據類型
print(df.head(2))#查看頭兩行
print(df.tail(3))#查看尾部三行
print(df.index)#顯示索引,同理下面是顯示列和屬性的
print(df.columns)
print(df.values)
print(df.describe())#describe函數對於數據的快速統計彙總
print(df.T)#輸出其轉置矩陣
print(df.sort_index(axis=1,ascending=True))#按軸排序 ascending設置是否允許降序
print(df.sort_values(by=‘B’))#按值排序,把B那一列的按順序排列了,默認逆序

選擇屬性

dg=pd.DataFrame(np.random.rand(5,4),index=dates,columns=list(‘abcd’))
print(dg)
print(dg.loc[‘2019-03-22’:‘2019-03-24’,[‘a’,‘b’]])#切片 切行,切列 .loc
print(dg.loc[‘2019-03-23’:,‘a’])#切到具體點 可以去掉’:'只看那一點 不去掉的話把0323之後所有的都給切出來
print(dg.loc[:,[‘b’,‘c’]])
print(dg.at[dates[4],‘a’])#at主要是訪問標量的
print(dg.loc[:‘2019-03-22’,‘a’])#把a的中括號去掉可以不顯示a
print(dg.iloc[3])#選擇行
print(dg.loc[dates[1],list(‘abcd’)])#方法等價於上面
print(dg.iloc[3:5,2:4])#iloc可以通過數值切片 總感覺像intloc
print(dg.iloc[1,1])#直接選擇切具體位置,快速訪問
print(dg.iat[2,2])#快速訪問標量
dg2=dg.copy()
dg2[‘e’]=list(‘12345’)
print(dg2)
print(dg2[dg2[‘e’].isin([‘2’,‘4’])])#這裏使用isin方法進行過濾,找出在第e列有沒有2,4兩個屬性,如果有則輸出。如果去掉最外層dg2[]則會輸出所有行,true或者false

reindex:修改索引

xl=pd.DataFrame(index=list(‘8910’),columns=list(‘1234’))
xl_1=xl.reindex(index=[5,6,7,8,9,1,0])
print(xl_1)

#缺失值處理 pandas裏面缺失值都是用nan表示的,
#去掉包含缺失值的行: df.dropna(how=‘any’) 通常情況下刪除行用axis=0 刪除列的話aixs=1
how=any是刪除所有的不管是列還是行只要是出現nan的位置

#df.fillna(value=?)缺失值替換可以是value=5 或者直接給他個字符串

#判斷是否爲nan用pd.isnull(你的創建的數據)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章