pandas尾部添加一条_Numpy与Pandas
生活随笔
收集整理的這篇文章主要介紹了
pandas尾部添加一条_Numpy与Pandas
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Numpy
#導(dǎo)入numpy包 import numpy as np ##from numpy import * #定義數(shù)組 #一維數(shù)組 a=np.array([1,2,3,4]) #二維數(shù)組 b=np.array([(1,2,3),(4,5,6)]) #定義數(shù)組類型 c=np.array([(1,2),(3,4)],dtype=complex) #array([[ 1.+0.j, 2.+0.j],[ 3.+0.j, 4.+0.j]])#數(shù)組的維數(shù) a.shape #(4,) #數(shù)組軸的個(gè)數(shù) a.ndim #1 #數(shù)組的元素類型 a.dtype #dtype('int32') #數(shù)組的元素類型的名稱 a.dtype.name #'int32' #數(shù)組中每個(gè)元素的字節(jié)大小 #一個(gè)元素類型為float64的數(shù)組itemsiz屬性值為8(=64/8) #一個(gè)元素類型為complex32的數(shù)組item屬性為4(=32/8). a.itemsize #4 #數(shù)組中元素個(gè)數(shù) a.size #4#全零數(shù)組 np.zeros((2,2)) #全1數(shù)組 np.ones((2,3,4)) array([[[ 1., 1., 1., 1.],[ 1., 1., 1., 1.],[ 1., 1., 1., 1.]],[[ 1., 1., 1., 1.],[ 1., 1., 1., 1.],[ 1., 1., 1., 1.]]]) #內(nèi)容隨機(jī)并且依賴與內(nèi)存狀態(tài)的數(shù)組。默認(rèn)創(chuàng)建的數(shù)組類型(dtype)都是float64。 empty((2,2)) #創(chuàng)建數(shù)列,并變?yōu)槿形辶小?np.arange(15).reshape(3,5)#基本運(yùn)算 a=array([1,2,3]) b=array([4,5,6]) c=b-a #array([3,3,3]) a**2 #array([1,4,9]) a<3 #array([True,True,False],dtype=bool) ## * dot(a,b)(矩陣乘法) ## *= +=被用來更改已存在數(shù)組而不創(chuàng)建一個(gè)新的數(shù)組 ## a.sum() a.sum(axis=0) 計(jì)算每一列的總和 a.max() a.min() a.min(axis=1) 計(jì)算每一行的最小值#一維數(shù)組 #索引 a[2] #切片 a[2:4] a[:8:2] a[::-1]#翻轉(zhuǎn)a #迭代 for i in a:#多維數(shù)組 #索引 a[2,3] #切片 a[2:4,1] #第三行和第四行的第二個(gè)元素 a[:,1] #每一行的第二個(gè)元素 a[1:3,:] #第二行和第三行的所有元素 a[-1] #最后一行的元素 #迭代 for row in a:#對(duì)每個(gè)數(shù)組中元素進(jìn)行運(yùn)算 for element in a.flat:print (element,end=",")Pandas
一維數(shù)據(jù)結(jié)構(gòu):Series
# Series 是帶有標(biāo)簽的一維數(shù)組,可以保存任何數(shù)據(jù)類型(整數(shù),字符串,浮點(diǎn)數(shù),Python對(duì)象等),軸標(biāo)簽統(tǒng)稱為索引 # Series 是一個(gè)自帶索引index 的數(shù)組,有三種創(chuàng)建方法 # 由字典創(chuàng)建 dic={'a':1,'b':2,'c':3} s=pd.Series(dic) # 由數(shù)組創(chuàng)建 arr=np.random.randn(5) s=pd.Series(arr,name='test') # 由標(biāo)量創(chuàng)建 s=pd.Series(2,index=range(3)) #位置下標(biāo) s[2] #標(biāo)簽索引 s = pd.Series(np.random.rand(3), index = ['a','b','c']) s['a'] s[['a','b']] #切片 s1 = pd.Series(np.random.rand(5)) s2 = pd.Series(np.random.rand(5), index = ['a','b','c','d','e']) print(s1[1:4],s1[4]) print(s2['a':'c'],s2['c']) print(s2[0:3],s2[3]) print('-----') # 注意:用index做切片是末端包含 print(s2[:-1]) print(s2[::2]) # 下標(biāo)索引做切片,和list寫法一樣 # 布爾型索引 s = pd.Series(np.random.rand(3)*100) s[4] = None # 添加一個(gè)空值 print(s) bs1 = s > 50 bs2 = s.isnull() bs3 = s.notnull() print(bs1, type(bs1), bs1.dtype) print(bs2, type(bs2), bs2.dtype) print(bs3, type(bs3), bs3.dtype) print('-----') # 數(shù)組做判斷之后,返回的是一個(gè)由布爾值組成的新的數(shù)組 # .isnull() / .notnull() 判斷是否為空值 (None代表空值,NaN代表有問題的數(shù)值,兩個(gè)都會(huì)識(shí)別為空值)print(s[s > 50]) print(s[bs3]) # 布爾型索引方法:用[判斷條件]表示,其中判斷條件可以是 一個(gè)語句,或者是 一個(gè)布爾型數(shù)組!#查看頭部、尾部數(shù)據(jù),默認(rèn)5條 s.head() s.tail() # 重新索引reindex # .reindex將會(huì)根據(jù)索引重新排序,如果當(dāng)前索引不存在,則引入缺失值 # fill_value參數(shù):填充缺失值 s1 = s.reindex(['c','b','a'],fill_value=0) #刪除 .drop s1=s.drop('c') s2=s.drop(['b','a']) # drop 刪除元素之后返回副本(inplace=False) #刪除缺失值 s.dropna() # 添加 s1[2] = 2 s2['a'] = 2 # 直接通過下標(biāo)索引/標(biāo)簽index添加值 s3 = s1.append(s2) # 通過.append方法,直接添加一個(gè)數(shù)組 # .append方法生成一個(gè)新的數(shù)組,不改變之前的數(shù)組 In [15]: # 修改 s['a'] = 2 s[['b','c']] = 2 # 通過索引直接修改,類似序列#獲取描述統(tǒng)計(jì)信息 s.describe()二維數(shù)組Dataframe:是一個(gè)表格型的數(shù)據(jù)結(jié)構(gòu),包含一組有序的列,其列的值類型可以是數(shù)值、字符串、布爾值等。 Dataframe中的數(shù)據(jù)以一個(gè)或多個(gè)二維塊存放,不是列表、字典或一維數(shù)組結(jié)構(gòu)。
# 創(chuàng)建方法 # 由字典創(chuàng)建 dic={'a':[1,2],'b':[2,3],'c':[3,4]} s=pd.DataFrame(dic) s1=pd.DataFrame(dic,columns=['b','d'])#重新指定列的順序,格式為list,如果現(xiàn)有數(shù)據(jù)中沒有該列(比如'd'),則產(chǎn)生NaN值 s2=pd.DataFrame(dic,index=['e','f','g']#重新定義index,格式為list,長度必須保持一致# 由Series組成的字典創(chuàng)建 s1 = {'one':pd.Series(np.random.rand(2)),'two':pd.Series(np.random.rand(3))} # 沒有設(shè)置index的Series s2 = {'one':pd.Series(np.random.rand(2), index = ['a','b']),'two':pd.Series(np.random.rand(3),index = ['a','b','c'])} # 設(shè)置了index的Series df1 = pd.DataFrame(s1) df2 = pd.DataFrame(s2) # 由Seris組成的字典 創(chuàng)建Dataframe,columns為字典key,index為Series的標(biāo)簽(如果Series沒有指定標(biāo)簽,則是默認(rèn)數(shù)字標(biāo)簽) # Series可以長度不一樣,生成的Dataframe會(huì)出現(xiàn)NaN值# 通過二維數(shù)組直接創(chuàng)建 s = np.random.rand(12).reshape(3,4) df1 = pd.DataFrame(s) df2 = pd.DataFrame(s, index = ['a', 'b', 'c'], columns = ['one','two','three','four']) # 可以嘗試一下index或columns長度不等于已有數(shù)組的情況 # 通過二維數(shù)組直接創(chuàng)建Dataframe,得到一樣形狀的結(jié)果數(shù)據(jù),如果不指定index和columns,兩者均返回默認(rèn)數(shù)字格式 # index和colunms指定長度與原數(shù)組保持一致# 由字典組成的列表 dic = [{'one': 1, 'two': 2}, {'one': 5, 'two': 10, 'three': 20}] print(dic) df1 = pd.DataFrame(dic) df2 = pd.DataFrame(dic, index = ['a','b']) df3 = pd.DataFrame(dic, columns = ['one','two']) # 由字典組成的列表創(chuàng)建Dataframe,columns為字典的key,index不做指定則為默認(rèn)數(shù)組標(biāo)簽 # colunms和index參數(shù)分別重新指定相應(yīng)列及行標(biāo)簽# 由字典組成的字典 data = {'Jack':{'math':90,'english':89,'art':78},'Marry':{'math':82,'english':95,'art':92},'Tom':{'math':78,'english':67}} df1 = pd.DataFrame(data) # 由字典組成的字典創(chuàng)建Dataframe,columns為字典的key,index為子字典的key df2 = pd.DataFrame(data, columns = ['Jack','Tom','Bob']) df3 = pd.DataFrame(data, index = ['a','b','c']) # columns參數(shù)可以增加和減少現(xiàn)有列,如出現(xiàn)新的列,值為NaN # index在這里和之前不同,并不能改變?cè)衖ndex,如果指向新的標(biāo)簽,值為NaN #標(biāo)簽索引 s = pd.DataFrame(np.random.rand(12).reshape(3,4), index = ['a','b','c'],columns=['one','two','three','four']) s['one']#只選擇一列輸出Series s[['one','two']]#選擇多列輸出DataFrame # s[col]一般用于選擇列,[]中寫列名;s[]中為數(shù)字時(shí),默認(rèn)選擇行,且只能進(jìn)行切片的選擇,不能單獨(dú)選擇(s[0]) s.loc['a']#只選擇一行輸出Series s.loc[['a','b']]#選擇多行輸出DataFrame#切片 s.loc['a':'c']# s.iloc[] - 按照整數(shù)位置(從軸的0到length-1)選擇行 s.iloc[0] s.iloc[[3,2,1]] s.iloc[1:3] s.iloc[::2]# 布爾型索引 bs1 = s > 50# 索引結(jié)果保留 所有數(shù)據(jù):True返回原數(shù)據(jù),False返回值為NaN bs2 = s['one']>50# 索引結(jié)果保留 單列判斷為True的行數(shù)據(jù),包括其他列 bs3 = s[['one','two']]>50# 索引結(jié)果保留 所有數(shù)據(jù):True返回原數(shù)據(jù),False返回值為NaN bs4= s.loc[['a','b']]>50# 索引結(jié)果保留 所有數(shù)據(jù):True返回原數(shù)據(jù),False返回值為NaN# 多重索引:比如同時(shí)索引行和列 # 先選擇列再選擇行 —— 相當(dāng)于對(duì)于一個(gè)數(shù)據(jù),先篩選字段,再選擇數(shù)據(jù)量 df['a'].loc[['one','three']] # 選擇a列的one,three行 df[['b','c','d']].iloc[::2] # 選擇b,c,d列的one,three行 df[df['a'] < 50].iloc[:2] # 選擇滿足判斷索引的前兩行數(shù)據(jù)#查看頭部、尾部數(shù)據(jù),默認(rèn)5條 s.head() s.tail() # .T 轉(zhuǎn)置 # 添加 s['four'] = 2#列 s.loc[4] = 2#行 # 修改 s['a'] = 2 s[['b','c']] = 2 #刪除 del s['one']#刪除列 s.drop(['d'], axis = 1)#刪除列,需要加上axis = 1,inplace=False → 刪除后生成新的數(shù)據(jù),不改變?cè)瓟?shù)據(jù)# 排序1 - 按值排序 .sort_values # 同樣適用于Series df1 = pd.DataFrame(np.random.rand(16).reshape(4,4)*100,columns = ['a','b','c','d']) print(df1.sort_values(['a'], ascending = True)) # 升序 print(df1.sort_values(['a'], ascending = False)) # 降序 # ascending參數(shù):設(shè)置升序降序,默認(rèn)升序 # 單列排序 df2 = pd.DataFrame({'a':[1,1,1,1,2,2,2,2],'b':list(range(8)),'c':list(range(8,0,-1))}) print(df2.sort_values(['a','c'])) # 多列排序,按列順序排序# 排序2 - 索引排序 .sort_index df1 = pd.DataFrame(np.random.rand(16).reshape(4,4)*100,index = [5,4,3,2],columns = ['a','b','c','d']) df2 = pd.DataFrame(np.random.rand(16).reshape(4,4)*100,index = ['h','s','x','g'],columns = ['a','b','c','d']) print(df1.sort_index()) print(df2.sort_index()) # 按照index排序 # 默認(rèn) ascending=True, inplace=False總結(jié)
以上是生活随笔為你收集整理的pandas尾部添加一条_Numpy与Pandas的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux搭建vsftp服务器_Linu
- 下一篇: springboot整合rocketmq