新聞中心
pandas是數(shù)據(jù)科學(xué)家必備的數(shù)據(jù)處理庫(kù),我們今天總結(jié)了10個(gè)在實(shí)際應(yīng)用中肯定會(huì)用到的技巧。

1、Select from table where f1=’a’ and f2=’b’
使用AND或OR選擇子集
dfb = df.loc[(df.Week == week) & (df.Day == day)]
OR的話是這樣
dfb = df.loc[(df.Week == week)|(df.Day == day)]
2、Select where in
從一個(gè)df中選擇一個(gè)包含在另外一個(gè)df的數(shù)據(jù),例如下面的sql
select * from table1 where field1 in (select field1 from table2)
我們有一個(gè)名為“days”的df,它包含以下值。
如果有第二個(gè)df:
可以直接用下面的方式獲取
days = [0,1,2]
df[df(days)]
3、Select where not in
就像IN一樣,我們肯定也要選擇NOT IN,這個(gè)可能是更加常用的一個(gè)需求,但是卻很少有文章提到,還是使用上面的數(shù)據(jù):
days = [0,1,2]
df[~df(days)]
使用~操作符就可以了
4、select sum(*) from table group by
分組統(tǒng)計(jì)和求和也是常見的操作,但是使用起來(lái)并不簡(jiǎn)單
df(by=['RepID','Week','CallCycleDay']).sum()
如果想保存結(jié)果或稍后使用它們并引用這些字段,請(qǐng)?zhí)砑?as_index=False
df.groupby(by=['RepID','Week','CallCycleDay'], as_index=False).sum()
使用as_index= false,可以表的形式保存列。
5、從一個(gè)表更另外一個(gè)表的字段
我們從一個(gè)df中更改了一些值,現(xiàn)在想要更新另外一個(gè)df,這個(gè)操作就很有用。
dfb = dfa[dfa.field1='somevalue'].copy()
dfb['field2'] = 'somevalue'
dfa.update(dfb)
這里的更新是通過(guò)索引匹配的
6、使用apply/lambda創(chuàng)建新字段
我們創(chuàng)建了一個(gè)名為address的新字段,它是幾個(gè)字段進(jìn)行拼接的。
dfa['address'] = dfa.apply(lambda row: row['StreetName'] + ', ' +
7、插入新行
插入新數(shù)據(jù)的最佳方法是使用concat。我們可以用有pd. datafframe .from_records一將新行轉(zhuǎn)換為df。
newRow = row.copy()
newRow.CustomerID = str(newRow.CustomerID)+'-'+str(x)
newRow.duplicate = True
df = pd.concat([df,pd.DataFrame.from_records([newRow])])
8、更改列的類型
可以使用astype函數(shù)將其快速更改列的數(shù)據(jù)類型
df = pd.read_excel(customers_.xlsx')
df['Longitude'] = df['Longitude'].astype(str)
df['Latitude'] = df['Longitude'].astype(str)
9、刪除列
使用drop可以刪除列
def cleanColumns(df):
for col in df.columns:
return df
10、地圖上標(biāo)注點(diǎn)
這個(gè)可能是最沒用的技巧,但是他很好玩。
這里我們有一些經(jīng)緯度的數(shù)據(jù)。
現(xiàn)在我們把它根據(jù)經(jīng)緯度在地圖上進(jìn)行標(biāo)注:
df_clustercentroids = pd.read_csv(centroidFile)
lst_elements = sorted(list(dfm.cluster2.unique()))
lst_colors = ['#%06X' % np.random.randint(0, 0xFFFFFF) for i in range(len(lst_elements))]
dfm["color"] = dfm["cluster2"]
dfm["color"] = dfm["color"].apply(lambda x:lst_colors[lst_elements.index(x)])
m = folium.Map(locatinotallow=[dfm.iloc[0].Latitude,dfm.iloc[0].Longitude], zoom_start = 9)
for index, row in 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)
for index, row in df_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
結(jié)果如下
網(wǎng)頁(yè)標(biāo)題:聊一聊十個(gè)Pandas的小技巧
當(dāng)前地址:http://www.5511xx.com/article/cohepoe.html


咨詢
建站咨詢
