Python Pandas基礎(chǔ)操作詳解
發(fā)布日期:2021-12-18 18:18 | 文章來源:站長之家
數(shù)據(jù)結(jié)構(gòu)&Series:
''' series {索引 + 數(shù)據(jù)} 形式 索引是自動(dòng)生成的 ''' #通過 list 創(chuàng)建 s1 = pd.Series([1, 2, 3, 4, 5]) #通過np數(shù)組創(chuàng)建 arr1 = np.arange(10) s2 = pd.Series(arr1) #自定義索引 s2 = pd.Series(arr1, index=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']) #單獨(dú)查看值或索引 print(s1.values) print(s1.index) #字典索引超出 會(huì)顯示nan 值 不會(huì)像數(shù)組創(chuàng)建series一樣報(bào)錯(cuò) #通過字典來創(chuàng)建series 由于字典無序 所以每次打印順序可能不同, 所以可以添加索引 保證順序 dict1 = {'姓名': '李寧', '班級(jí)': '三班', '年齡': '22'} print(dict1) s3 = pd.Series(dict1, index=['姓名', '班級(jí)', '年齡', '性別']) #判斷values是否為空nan print(s3.isnull()) #判斷values是否不為空 print(s3.notnull()) #通過下標(biāo)取數(shù)據(jù) print(s3[1]) #通過標(biāo)簽名取數(shù)字 print(s3['姓名']) #選取多個(gè) print(s2[[1, 5]]) #切片取值 print(s2[1:4]) #索引切邊 是 左閉右開 print(s2['b':'h']) #標(biāo)簽切片可以包含末端數(shù)據(jù) 如h #bool索引取值 print(s2[s2>5]) #索引與數(shù)據(jù)的對(duì)應(yīng)關(guān)系 不被 運(yùn)算所影響 #name 屬性 s2.name = '佳林' #數(shù)組對(duì)象名---values標(biāo)題 s2.index.name = '字母表'#索引名 ---- index標(biāo)題 #查看前三行 print(s2.head(3)) #查看后兩行 print(s2.tail(2))
DataFrame的構(gòu)建:
#構(gòu)造多類型字典 data = { 'a': [1, 2, 3, 4], 'b': (5, 6, 7, 8), 'c': np.arange(9, 13) } frame = pd.DataFrame(data) #查看行索引 print(frame.index) #查看列索引 print(frame.columns) #查看values print(frame.values)#返回nparray類型的二維數(shù)組 #指定行索引 frame = pd.DataFrame(data, index=['A', 'B', 'C', 'D']) #指定列行索引 frame = pd.DataFrame(data, index=['A', 'B', 'C', 'D'], columns=['a', 'b', 'c', 'd']) #series構(gòu)成的字典構(gòu)造dataframe pd1 = pd.DataFrame({'a': pd.Series(np.arange(5)), 'b': pd.Series(np.arange(3, 5)) }) #dataframe的每列元素類型必須統(tǒng)一 #通過字典構(gòu)造的字典來構(gòu)造dataframe(嵌套) data1 = { 'a': { 'apple': '3.6', 'banan': '3.5' }, 'b': { 'apple': '3.6', 'banan': '3.5', 'red': '3.7', 'yellow': '3.8' } } #最內(nèi)層字典的key是index #外層字典的key是columns #通過二位數(shù)組來構(gòu)造dataframe----默認(rèn)columns和index都是0-n arr1 = np.arange(12).reshape(3, 4) print(arr1) frame1 = pd.DataFrame(arr1) #字典構(gòu)造的列表 構(gòu)造 dataframe li = [{'apple': '3.6', 'orange': '2.5'}, {'apple': '4.8', 'orange': '2.8'}, {'apple': '2.4'}] li_data = pd.DataFrame(li) #Series構(gòu)成的列表 構(gòu)成dataframe l2 = [pd.Series(np.random.rand(3)), pd.Series(np.random.rand(3))] l2_data = pd.DataFrame(l2)
索引操作:
ps = pd.Series(range(5)) pd1 = pd.DataFrame(np.arange(9).reshape(3, 3), index=['a', 'b', 'c'], columns=['A', 'B', 'C']) #重新索引 reindex 創(chuàng)建一個(gè)符合新索引的新對(duì)象 ps2 = ps.reindex(['a', 'b', 'c', 'd', 'e']) print(ps2) #因?yàn)樾滤饕c之前的索引沒有對(duì)應(yīng)關(guān)系 所以values全為空!?。。?#dataframe行索引重建順序調(diào)整 pd2 = pd1.reindex(['a', 'b', 'c', 'd']) pd3 = pd1.reindex(columns= ['B', 'C', 'A', 'B'])
DataFrame基本操作:
np.random.seed(1) pd1 = pd.DataFrame(np.random.randint(0, 10, size=(3, 5)), columns=['a', 'b', 'c', 'd', 'e'], index=['A', 'B', 'C']) print(pd1) #和numpy一樣 進(jìn)行轉(zhuǎn)至 切片提取 # print(pd1.T) print(pd1[:'B']['e']) #第一個(gè)或只有一個(gè)[]默認(rèn)是行索引index 第二個(gè)[]是columns #增加列 pd1['f'] = [5, 5, 5] print(pd1) #刪除列 del(pd1['d']) print(pd1) #修改行索引名----只能賦值 1\直接賦值法 pd1.index = ['a', 'b'........] 2\自定義函數(shù)法 def test_map(x): return x+'_ABC' pd1.rename(index=test_map,inplace=True) #修改列索引名 1\直接賦值 pd1.columns = [] 2\用str進(jìn)行廣播操作 如整體去掉某符號(hào) pd1.columns = pd1.columns.str.strip('$') 3\函數(shù)法 pd1.columns = pd1.columns.map(lambda x:x[1:]) 4\rename屬性 # 直接法(好處:也可只修改特定的列)----字典values替代key df.rename(columns=('$a': 'a', '$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}, inplace=True) # 函數(shù)法 df.rename(columns=lambda x:x.replace('$',''), inplace=True) #提取行、列的loc和iloc #iloc是按索引位置提取 #loc是按標(biāo)簽提取 df.loc[:, 'a'] #提取a列 df.loc[:, ['a', 'c']] #提取ac列 df.loc[1] #提取行標(biāo)簽為1的行 df.iloc[1]#提取行位置為1的行也就是第二行 df.loc[:2]#提取多行 #loc沒有左閉右開 df.loc[0:1, 'b']#提取行索引0-1包括1 的‘b'列 df1.loc['a':'B', 'c':'d']#按標(biāo)簽提取某范圍的行列 #多條件 df[(df['a']<=2) & (df['b']>=5)] df.loc[(df['a']<=2) & (df['b']>=5)] # 或 條件 不能使用 or df[(df['a']<=2) | (df['b']>=5)] df.loc[(df['a']<=2) | (df['b']>=5)]
廣播運(yùn)算:
arr = np.arange(12).reshape(3, 4) print(arr) #廣播 每一行都減去第一行 print(arr-arr[0]) #默認(rèn)series的行索引 匹配的是dataframe的列索引 df1 = pd.DataFrame(np.arange(12).reshape(4, 3), index=['a', 'b', 'c', 'd'], columns=list('ABC')) s3 = df1.iloc[0] #取第一行 print(s3) print(df1 - s3) #沿著列運(yùn)算 print(df1.sub(s4, axis= 0))
索引增刪改查:
#增 ##series ps[4] = 9 print(ps) ps1 = pd.Series({'v': 's', 'f': 's'}) pss = ps.append(ps1) #append拼接 這個(gè)方法不會(huì)影響原有數(shù)據(jù) ##dataframe ###增加列 df['d'] = [9, 8, 9] ###插入 df.insert(0, 'M', 1)#在第0列插入M全為1 ##高級(jí)標(biāo)簽索引--增加行l(wèi)oc df.loc['q'] = 1 row = {'M': 's', 'a': 'b', 'b': 'w', 'c': 'w', 'd': 8} dfnew = df.append(row, ignore_index=True) #ignore_index:如果設(shè)置為true,則無視表的index,直接合并,合并后生成新的index。 #刪 del ps[0] #del只能刪除dataframe的列 del df['M'] #*******drop******刪除軸上的數(shù)據(jù) #dataframe刪除行 print(df.drop(['S', 'W'])) #指定軸刪除列 print(df.drop(['a', 'c'], axis=1)) ps = pd.Series(range(1, 5)) #改 ps[0] = 888 print(ps) df.a = 6 #修改行數(shù)據(jù) df.loc['S'] = 888 #修改單個(gè)元素 df.loc['D', 'b'] = 8848
字符串元素處理:
in:
data = {'a': 'aeac@qq.com', 'b': 'stevan@famil.com', 'c': 'asda@asd.com', 'd': np.nan} data = pd.Series(data) print(data) print(data.isnull()) #字符串查找 print(data.str.contains('qq')) #分割 print(data.str.split(r'@')) print(data.str.findall(r'@')) #切片 print(data.str[:5])
out:
aaeac@qq.com b stevan@famil.com c asda@asd.com d NaN dtype: object a False b False c False d True dtype: bool a True b False c False dNaN dtype: object a[aeac, qq.com] b [stevan, famil.com] c [asda, asd.com] d NaN dtype: object a [@] b [@] c [@] d NaN dtype: object a aeac@ b steva c asda@ dNaN dtype: object
數(shù)據(jù)規(guī)整:
pd.merge(data1, data2, on= '按照哪一行合并', how = 'left或right或outer或inner') pd.merge(df_obj5, df_obj6, how='outer', left_index=True, right_index=True) pd.merge(df_obj3, df_obj4, left_on='key', right_index=True) pd.concat([df1, df2], join='inner\outer', axis=1 stack 列索引在最外層 columns在內(nèi)層 變成series 外層索引為index內(nèi)層索引變成columns--unstack() g = df1.groupby(by='fruit') for name,group in g: print(name) print('-'*30) print(group) apple ------------------------------ fruit color price 0 applered 8.5 3 apple cyan 7.8 banana ------------------------------ fruitcolor price 1 banana yellow 6.8 4 banana cyan 6.4 orange ------------------------------ fruitcolor price 2 orange yellow 5.6 #利用字典來獲取具體分組名的dataframe s = dict(list(df1.groupby(by='fruit'))) s['apple'] def diff(arr): return arr.max() - arr.min() df1.groupby(by='fruit')['price'].agg(diff)
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注本站的更多內(nèi)容!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
相關(guān)文章