1. 程式人生 > >python 的一些常用的用法

python 的一些常用的用法

重點:
dataframe.apply(function,axis)對一行或一列做出一些操作(axis=1則為對某一列進行操作,此時,apply函式每次將dataframe的一行傳給function,然後獲取返回值,將返回值放入一個series)
python去空格:字串.strip()

待解決:
dataframe.assign()應該怎麼用?

(1)讀入資料後先把 城市 那一列城市名中的空格去掉

對一列資料去空格的方法:

def qukong(hang):
return hang['city'].strip()
dataframe['city']=dataframe.apply(qukong,axis=1) # axis=1表示對每一行做相同的操作
dataframe

###dataframe.apply用於對一行或一列做一些相同的操作

(2)呼叫百度地圖API查詢各城市經緯度(查詢出的結果我們用dict儲存)

def p2l(name):
# 1、設定url和3個引數(輸出格式,key,要翻譯的地址)
url = 'http://api.map.baidu.com/geocoder/v2/'
output = 'json'
ak = 'sXZHPZahdMeK3Gy3uC7ZeRQrVbZDnP1G'
address = quote(name)

# 2、拼接get請求(url?引數1=值1&引數2=值2&引數3=值3)
request = url + '?' + 'address=' + address + '&output=' + output + '&ak=' + ak

# 3、urlopen傳送請求,獲得response
response_file = urlopen(request)

# 4、讀取response字串
response_str = response_file.read().decode()

# 5、str轉json
response_json = json.loads(response_str)

# 6、讀json
lat=response_json['result']['location']['lat']
lng=response_json['result']['location']['lng']

return [lat,lng]

list_place=list(set(dataframe['city']))
dict_loc={}
for elem in list_place:
dict_loc[elem]=p2l(elem)
dict_loc


(3)將查詢到的經緯度放入dataframe中
def add_lat(hang):
return dict_loc[hang['city']][0]

def add_lng(hang):
return dict_loc[hang['city']][1]

dataframe['city_lat']=dataframe.apply(add_lat,axis=1)
dataframe['city_lng']=dataframe.apply(add_lng,axis=1)

(4)從dataframe的日期一列中提取出 年、月、日 三個新列
def add_year(hang):
date=hang['date']
tmplist=date.split('/')
return tmplist[0]

def add_month(hang):
date=hang['date']
tmplist=date.split('/')
return tmplist[1]

def add_day(hang):
date=hang['date']
tmplist=date.split('/')
return tmplist[2]

dataframe['year']=dataframe.apply(add_year,axis=1)
dataframe['month']=dataframe.apply(add_month,axis=1)
dataframe['day']=dataframe.apply(add_day,axis=1)

(5)獲取星期幾
from datetime import datetime,date

dayOfWeek = datetime.now().weekday()
print dayOfWeek

dayOfWeek = datetime.today().weekday()
print dayOfWeek
datetime類的weekday()方法可以獲得datetime是星期幾,注意weekday() 返回的是0-6是星期一到星期日