Pandas操做 python使用pandas讀取csv import pandas as pd #數據篩選 usetTable = pd.read_csv(filename,header = 0) mask = True ^ userTable['ID'].isin(['',''])&..... show = userTable[mask] #例子,包含6105的行 userTable[userTable['ID'].isin(['6105'])] userTable[userTable['ID'].isin([6105])] #統計某種數據出現的次數 result = userTable.group(['列名1','列名2']).size().result_index(name = 'count') #錶鏈接(列名一致) result = pd.merge(result1,result2,how = 'left', on=['列名1','列名2']) #錶鏈接(列名不一致) result = pd.merge(result1,result2,how = 'left', left_on = '列名',right_on = '列名') #去除重複項 result = result1[~result1.duplicated(subset = ['列名1','列名2'], keep = 'last')] #對指定項進行累加,展現 result = result1.groupby([])['count'].sum().reset_index() #選取用戶在不一樣地點的最大時間 result = result1.groupby([])['time'].max().reset_index() #返回特定值的行 table[tabel.flag == 1] #loc,iloc,ix ''' loc經過標籤索引讀取行數據 iloc經過行號索引 ix結合兩種 ''' #取某幾列數據 iloc[:,[1,2]] #python中的三元表達式 h = "變量1" if a>b else "變量2" table.groupby('b').['key'].apply(lambda i: i.iloc[1] if len(i)>2 else len(i))#此處的i應用於每一行或每一列,自動匹配 #按照年齡排序 students = [('joh','A',15),('jat','B',12),('dev','B',10)]#tuple list1 = sorted(students,key = lambda student:students[2])#list sorted(cmp,key,reverse)#reverse默認爲False,升序。 #過濾,每一行返回的是最大值 index1 = result.groupby()[].transform(max) index2 = ( index1 == result['count']) #取特定列 usetTable[['列名1','列名2']] #刪除特定列 userTable.drop('列名',axis =1) axis = 0 表示沿着行標籤方向執行方法 axis = 1 表示沿着列標籤方向執行方法 #返回特定數據所在的行號 d = df[(df.Boolcol ==3 )& (df.attr == 32)].index.tolist() #查看某幾列的值 df.head(n) #獲取行號 raw = df.shape[0] #經過行號獲取其餘數據 df.ix[d]['數據'] #list轉array np.array([list]) #array存爲csv pd.DataFrame(data = array).to_csv('yy',mode = 'a',header=False) #獲取某一列不重複的數據及個數 len(df['列名'].unique()) #python做圖 #設置X軸 pd.set_index('列名') pd.plot.line() pd.random.randn(10,4) fig, axes = plt.subplots(2,1) pd.plot(kind ='bar', ax = axe[0]) #垂直柱狀圖 kind = 'bar' #垂直密度圖 kind = 'kde' #水平柱狀圖 kind = 'barh' #指定在某個子圖上做圖 ax = axe[0] #生成堆積柱狀圖 stacked = True #餅圖 pd.plot.pie(subplots = True) pd.plot.scatter(x = '列名',y = '列名') #使用pd.Series把dataframe轉成Series pd.series(df['列名'].values,index = df['']) #返回列數 userTable.colums.size #將組內的列表合併,數據聚合 result = table.groupby(['id']).aggregate(lambda x: list(x)) #python去除字符串兩端的符號 strip()去除首末 lstrip()去除左邊 rstrip()去除右邊 #把含有Nan的行刪除 df.dropna() #刪除列爲空的行 table = pd.read_csv("", dtype = {'CUST_ID':str}) mask = table['CUST_ID'].isnull() table = table[~mask] #取列名 DataFrame.colums.values.tolist() #轉化爲python可識別的數值 np.nan:nan np.Inf:Inf #對分組後的數據採起不一樣的運算方式 data = df.groupby('A') data.agg({'B':'mean', 'c':'sum'}) #按照A分組後,對多列採起相同的聚合方式 df.groupby('A').apply(np.mean) #將某列數據按數據值分紅不一樣範圍,進行分組運算 df = pd.DataFrame({'Age'}:np.random.randint(20,70,100), 'sex':np.random.choice(['male','female'],size=(10))) #生成時間格式 pd.dta_range('2018-6-20', periods =20, freq = '5min') #按照範圍分組 age_groups = pd.cut(df['age'], bins = [19,40,65,np.inf]) result = df.groupby(age_groups).max() #生成交叉表 pd.crosstab(age_groups,df['sex']) #分組後,轉爲dict A = dic(list(df.groupby('key'))) A['a'] temp = df.groupby('type') for name,group in temp: print(name)#str print(group)#DataFrame fo x in temp: print(x)#tuple agg使用:針對不一樣的列,應用不一樣的聚合函數 #按照A分組後,對另外一列採起不一樣的聚合方式 df.groupby('A')['B'].agg({'mean':np.mean,'std':np.std}) #按照A分組後,對不一樣的列採起不一樣的處理方式 df.groupby('A').agg({'B':[np.mean,'sum'],'C':['count',np.std]}) #分組後,按照某幾列排序 #按照時間排序 result.groupby(['a.id'],group_keys = False).apply( lambda g: g.sort_value('b.time',ascending = True)) #按照指定列排序 DF.sort_values(by = '列名', ascending = True) #取某一列的值 tble['列名'].str[0:10] #增長一列 table['new'] = talbe['列名'].str[0:10] #lambda函數 my_lambda = lambda arg: arg+1 result = my_lambda(123) 等價於 def func(arg): return arg+1 result = func(123) #讀取csv問價 pd.read_csv(error_bad_lines = False(跳過錯誤行), quoting = CSV.QUOTE_NONE(指定字符使用時不收分隔符影響)) #pandas按照正則匹配 index = table['b.str'].str.contains(r'^\$.*') result = table[index] #獲取特定值所在的列 result[result['a.id' == 2018]] result[result['a.time' >= '2018-04-01']] #保留第一次出現的行 df.drop_duplicates(subset = ['',''],keep='first')