pandas是数据科学家必备的数据处理库。今天我们总结了10个在实际应用中肯定会用到的技巧。1.Selectfromtablewheref1='a'andf2='b'使用AND或OR选择子集dfb=df.loc[(df.Week==week)&(df.Day==day)]OR就是这样dfb=df.loc[(df.Week==week)|(df.Day==day)]2.selectwherein从一个df中选择另一个df中包含的数据,比如下面的sqlselect*从table1wherefield1in(selectfield1fromtable2)我们有一个名为“days”的df,它包含以下值。如果有第二个df:days=[0,1,2]df[df(days)]可以直接通过下面的方式得到。3.选择wherenotinislikeIN,我们也必须选择NOTIN,这个可能是比较常用的需求,但是很少有文章提到,还是用上面的数据:days=[0,1,2]df[~df(days)]在上面使用~运算符4.selectsum(*)fromtablegroupbygroupstatisticsandsummation也是常用的操作,但是不好用df(by=['RepID','Week','CallCycleDay']).sum()如果要保存结果或以后使用它们并引用这些字段,请添加as_index=Falsedf.groupby(by=['RepID','Week','CallCycleDay'],as_index=False).sum()使用as_index=false,可以将表格保存到列中。5.从一个表到另一个表的字段我们从一个df改了一些值,现在我们要更新另一个df,这个操作很有用。dfb=dfa[dfa.field1='somevalue'].copy()dfb['field2']='somevalue'dfa.update(dfb)这里的更新是通过索引匹配6.使用apply/lambda创建新字段我们创建了一个名为地址的新字段,它是几个字段的串联。dfa['address']=dfa.apply(lambdarow:row['StreetName']+','+7,insertingnewrows插入新数据最好的方法是使用concat。我们可以使用pd.datafframe.from_recordsone将新行转换为df.newRow=row.copy()newRow.CustomerID=str(newRow.CustomerID)+'-'+str(x)newRow.duplicate=Truedf=pd.concat([df,pd.DataFrame.from_records([newRow])])8.改变列的类型,可以使用astype函数快速改变列的数据类型df=pd.read_excel(customers_.xlsx')df['Longitude']=df['Longitude'].astype(str)df['Latitude']=df['Longitude'].astype(str)9.删除列使用drop删除列defcleanColumns(df):forcolindf.columns:returndf10,Markingpointsonthemap这可能是最无用的trick,但是很好玩,这里我们有一些经纬度数据。现在我们把它根据纬度在地图上进行标记:df_clustercentroids=pd.read_csv(centroidFile)lst_elements=sorted(list(dfm.cluster2.unique()))lst_colors=['#%06X'%np.random.randint(0,0xFFFFFF)foriinrange(len(lst_elements))]dfm["color"]=dfm["cluster2"]dfm["color"]=dfm["color"].apply(lambdax:lst_colors[lst_elements.index(x)])m=folium.Map(locatinotallow=[dfm.iloc[0].Latitude,dfm.iloc[0].Longitude],zoom_start=9)对于索引,dfm.iterrows()中的行:folium.CircleMarker(locatinotallow=[float(row['Latitude']),float(row['Longitude'])],radius=4,popup=str(row['RepID'])+'|'+str(row.CustomerID),color=row['color'],fill=True,fill_color=row['color']).add_to(m)forindex,rowindf_clustercentroids.iterrows():folium.Marker(locatinotallow=[float(row['Latitude']),float(row['Longitude'])],popup=str(index)+'|#='+str(dfm.loc[dfm.cluster2==index].groupby(['cluster2'])['CustomerID'].count().iloc[0]),icnotallow=folium.Icon(color='black',icon_color=lst_colors[index]),tooltip=str(index)+'|#='+str(dfm.loc[dfm.cluster2==index].groupby(['cluster2'])['CustomerID'].count().iloc[0])).add_to(m)m结果如下
