关于人工智能:10个Pandas的小技巧

3次阅读

共计 2605 个字符,预计需要花费 7 分钟才能阅读完成。

pandas 是数据科学家必备的数据处理库,咱们明天总结了 10 个在理论利用中必定会用到的技巧

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

从一个 df 中抉择一个蕴含在另外一个 df 的数据,例如上面的 sql

 select * from table1 where field1 in (select field1 from table2)

咱们有一个名为“days”的 df,它蕴含以下值。

如果有第二个 df:

能够间接用上面的形式获取

 days = [0,1,2]
 df[df(days)]

3、Select where not in

就像 IN 一样,咱们必定也要抉择 NOT IN,这个可能是更加罕用的一个需要,然而却很少有文章提到,还是应用下面的数据:

 days = [0,1,2]
 df[~df(days)]

应用

~

操作符就能够了

4、select sum(*) from table group by

分组统计和求和也是常见的操作,然而应用起来并不简略

 df(by=['RepID','Week','CallCycleDay']).sum()

如果想保留后果或稍后应用它们并援用这些字段,请增加 as_index=False

 df.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 创立新字段

咱们创立了一个名为 address 的新字段,它是几个字段进行拼接的。

 dfa['address'] = dfa.apply(lambda row: row['StreetName'] + ',' + 
              row['Suburb'] + ',' + str(row['PostalCode']),axis=1)

7、插入新行

插入新数据的最佳办法是应用 concat。咱们能够用有 pd. datafframe .from_records 一将新行转换为 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 函数将其疾速更改列的数据类型

 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:
     if col[0:7] == "Unnamed":
       df.drop(col, inplace=True, axis=1)
   return df

10、地图上标注点

这个可能是最没用的技巧,然而他很好玩

这里咱们有一些经纬度的数据

当初咱们把它依据经纬度在地图上进行标注:

 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(location=[dfm.iloc[0].Latitude,dfm.iloc[0].Longitude], zoom_start = 9)
 
 for index, row in dfm.iterrows():
   folium.CircleMarker(location=[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(location=[float(row['Latitude']), float(row['Longitude'])],popup=str(index) + '|#=' + str(dfm.loc[dfm.cluster2==index].groupby(['cluster2'])['CustomerID'].count().iloc[0]),icon=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

后果如下

https://avoid.overfit.cn/post/5165608a2a274f9e9c0f6ba0db92f42d

作者:Shaun Enslin

正文完
 0