此教程適合有pandas基礎(chǔ)的童鞋來看,很多知識點會一筆帶過,不做詳細解釋
Pandas數(shù)據(jù)格式
DataFrame:每個column就是一個Series
基礎(chǔ)屬性shape,index,columns,values,dtypes,describe(),head(),tail()
統(tǒng)計屬性Series: count(),value_counts(),前者是統(tǒng)計總數(shù),后者統(tǒng)計各自value的總數(shù)
df.isnull() df的空值為True
df.notnull() df的非空值為True
df.rename(columns = {'key':'key2'},inplace=True)
isin #計算一個“Series各值是否包含傳入的值序列中”的布爾數(shù)組unique #返回唯一值的數(shù)組value_counts #返回一個Series,其索引為唯一值,值為頻率,按計數(shù)降序排列
df.drop(labels, axis=1)# 按列(axis=1),丟棄指定label的列,默認按行。。。
# 默認axi=0(行);1(列),how=‘a(chǎn)ny’df.dropna()#每行只要有空值,就將這行刪除df.dropna(axis=1)#每列只要有空值,整列丟棄df.dropna(how='all')# 一行中全部為NaN的,才丟棄該行df.dropna(thresh=3)# 每行至少3個非空值才保留
df.fillna(0)df.fillna({1:0,2:0.5}) #對第一列nan值賦0,第二列賦值0.5df.fillna(method='ffill') #在列方向上以前一個值作為值賦給NaN
# 將df的A列中 -999 全部替換成空值df['A'].replace(-999, np.nan)#-999和1000 均替換成空值obj.replace([-999,1000], np.nan)# -999替換成空值,1000替換成0obj.replace([-999,1000], [np.nan, 0])# 同上,寫法不同,更清晰obj.replace({-999:np.nan, 1000:0})
df.duplicated()#兩行每列完全一樣才算重復(fù),后面重復(fù)的為True,第一個和不重復(fù)的為false,返回true #和false組成的Series類型df.duplicated('key')#兩行key這一列一樣就算重復(fù)df['A'].unique()# 返回唯一值的數(shù)組(類型為array)df.drop_duplicates(['k1'])# 保留k1列中的唯一值的行,默認保留第一行df.drop_duplicates(['k1','k2'], take_last=True)# 保留 k1和k2 組合的唯一值的行,take_last=True 保留最后一行
# 默認axis=0,按行索引對行進行排序;ascending=True,升序排序df.sort_index()# 按列名對列進行排序,ascending=False 降序df.sort_index(axis=1, ascending=False)
# 按值對Series進行排序,使用order(),默認空值會置于尾部s = pd.Series([4, 6, np.nan, 2, np.nan])s.order()df.sort_values(by=['a','b'])#按列進行排序
a=Series([7,-5,7,4,2,0,4])a.rank()#默認method='average',升序排名(ascending=True),按行(axis=0)#average 值相等時,取排名的平均值#min 值相等時,取排名最小值#max 值相等時,取排名最大值#first值相等時,按原始數(shù)據(jù)出現(xiàn)順序排名
# 返回一個新的DataFrame,更新index,原來的index會被替代消失# 如果dataframe中某個索引值不存在,會自動補上NaNdf2 = df1.reindex(['a','b','c','d','e'])# fill_valuse為原先不存在的索引補上默認值,不在是NaNdf2 = df1.reindex(['a','b','c','d','e'], fill_value=0)# inplace=Ture,在DataFrame上修改數(shù)據(jù),而不是返回一個新的DataFramedf1.reindex(['a','b','c','d','e'], inplace=Ture)# reindex不僅可以修改 索引(行),也可以修改列states = ["Texas","Utah","California"]df2 = df1.reindex( columns=states )
# 將columns中的其中兩列:race和sex的值設(shè)置索引,race為一級,sex為二級# inplace=True 在原數(shù)據(jù)集上修改的adult.set_index(['race','sex'], inplace = True) # 默認情況下,設(shè)置成索引的列會從DataFrame中移除# drop=False將其保留下來adult.set_index(['race','sex'], inplace = True)
df.reset_index()
[]
只能對行進 行(row/index) 切片,前閉后開df[0:3],df[:4],df[4:]
where 布爾查找
df[df["A"]>7]
# 返回布爾值s.isin([1,2,3])df['A'].isin([1,2,3])df.loc[df['A'].isin([5.8,5.1])]選取列A中值為5.8,5.1的所有行組成dataframe
df.query(" A>5.0 & (B>3.5 | C<1.0) ")
# df.loc[A,B] A是行范圍,B是列范圍df.loc[1:4,['petal_length','petal_width']]# 需求1:創(chuàng)建一個新的變量 test# 如果sepal_length > 3 test = 1 否則 test = 0df.loc[df['sepal_length'] > 6, 'test'] = 1df.loc[df['sepal_length'] <=6, 'test'] = 0# 需求2:創(chuàng)建一個新變量test2 # 1.petal_length>2 and petal_width>0.3 = 1 # 2.sepeal_length>6 and sepal_width>3 = 2 3.其他 = 0df['test2'] = 0df.loc[(df['petal_length']>2)&(df['petal_width']>0.3), 'test2'] = 1df.loc[(df['sepal_length']>6)&(df['sepal_width']>3), 'test2'] = 2
df.iloc[1:4,:]
df1.ix[0:3,['sepal_length','petal_width']]
alist = [1,2,3,4]map(lambda s : s+1, alist)#map就是將自定義函數(shù)應(yīng)用于Series每個元素df['sepal_length'].map(lambda s:s*2+1)[0:3]
These are techniques to apply function to element, column or dataframe.Map: It iterates over each element of a series. df[‘column1’].map(lambda x: 10+x), this will add 10 to each element of column1.df[‘column2’].map(lambda x: ‘AV’+x), this will concatenate “AV“ at the beginning of each element of column2 (column format is string).Apply: As the name suggests, applies a function along any axis of the DataFrame.df[[‘column1’,’column2’]].apply(sum), it will returns the sum of all the values of column1 and column2.df0[['data1']].apply(lambda s:s+1)ApplyMap: 對dataframe的每一個元素施加一個函數(shù)func = lambda x: x+2df.applymap(func), dataframe每個元素加2 (所有列必須數(shù)字類型)
# 使用DataFrame模糊篩選數(shù)據(jù)(類似SQL中的LIKE)# 使用正則表達式進行模糊匹配,*匹配0或無限次,?匹配0或1次df_obj[df_obj['套餐'].str.contains(r'.*?語音CDMA.*')] # 下面兩句效果一致df[df['商品名稱'].str.contains("四件套")]df[df['商品名稱'].str.contains(r".*四件套.*")]