99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀Python數(shù)據(jù)分析常用高階函數(shù)大全
Python數(shù)據(jù)分析常用高階函數(shù)大全
2019-10-24
收藏
Python數(shù)據(jù)分析常用高階函數(shù)大全

作者 | CDA數(shù)據(jù)分析師

來源 | CDA數(shù)據(jù)科學(xué)研究院

map

map(function,iterable,...)

第一個參數(shù),是函數(shù)

第二個參數(shù),是可迭代對象(列表、字符串等)

map返回的是對可迭代對象里的每個元素進(jìn)行函數(shù)運(yùn)算的結(jié)果

例如:

def fun(x):
 return x*3
l=[0,1,2,3,4,5]
l_m=map(fun,l)
print(list(l_m))

原本是

[0,1,2,3,4,5]

運(yùn)行map后返回的結(jié)果是

[0, 3, 6, 9, 12, 15]

相當(dāng)于對可迭代對象里的每個元素都進(jìn)行了*3的運(yùn)算,也就是我們給定函數(shù)運(yùn)算的方式,然后返回一個值。

這里需要注意的是 ,map()直接返回的是一個的對象

我們需要利用list函數(shù)將它里邊的元素釋放出來。

Python數(shù)據(jù)分析常用高階函數(shù)大全

與此同時,map函數(shù)的好朋友就是lambda,lambda匿名函數(shù)經(jīng)常作為map的第一個參數(shù)進(jìn)行組合使用

例如

print(list(map(lambda x:x*3,l)))

返回的結(jié)果依舊是

[0, 3, 6, 9, 12, 15]

zip

zip()將多個可迭代對象的元素組合成為為一個元組序列

l = ['a', 'b', 'c']
n = [1, 2, 3]
print(list(zip(l,n)))

[('a', 1), ('b', 2), ('c', 3)]

和map類似,zip返回的也是一個zip的元組迭代器對象,我們需要使用list將它的元素釋放出來

filter

filter(function,sequence)

第一個參數(shù)是函數(shù),第二個參數(shù)是可迭代對象

最后返回的是,可迭代對象里滿足函數(shù)要求的元素。

因此也稱之為過濾。

long = [1,2,3,4,5]
list(filter(lambda x:x%2==0,long)) # 找出偶數(shù)。
# filter函數(shù)返回的是迭代器,所以需要用list轉(zhuǎn)換,進(jìn)行釋放元素。
# 輸出:
[2, 4]

reduce

reduce(function,iterable)

第一個參數(shù)是函數(shù),第二個參數(shù)是可迭代對象(列表,字符串等)

導(dǎo)入reduce的時候需要用到funtools這模塊

from functools import reduce 
lk = [2,3,4]
reduce(lambda y,z:z+y,lk)
# out : 9

運(yùn)算的步驟是

2+3=5

5+4=9

最后返回的結(jié)果就是9

Python數(shù)據(jù)分析常用高階函數(shù)大全

apply

DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), kwds)

apply函數(shù)是pandas.DataFrame里的方法

例如

kk是pd.DataFrame的類型的數(shù)據(jù)

0
0 0a
1 1b
2 2c
3 3d
4 4e
kk["new"]=kk[0].apply(lambda x:x[-1] )
kk
0 new
0 0a a
1 1b b
2 2c c
3 3d d
4 4e e

sort_values

參數(shù)

DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last')

參數(shù)說明

axis:{0 or ‘index’, 1 or ‘columns’} 
#default 0,默認(rèn)按照索引排序,即縱向排序,如果為1,則是橫向排序 
by:str or list of str
#如果axis=0,那么by="列名";如果axis=1,那么by="行名"; 
ascending: #布爾型,True則升序,可以是[True,False],即第一字段升序,第二個降序 
inplace: #布爾型,是否用排序后的數(shù)據(jù)框替換現(xiàn)有的數(shù)據(jù)框 
kind:排序方法, #{‘quicksort’, ‘mergesort’, ‘heapsort’}, default ‘quicksort’。
na_position : #{‘first’, ‘last’}, default ‘last’,默認(rèn)缺失值排在最后面
import pandas as pd
import numpy as np
a = np.random.randint(low=0,high=100,size=(11,2))
data = pd.DataFrame(a)
data.apply(lambda x:x*10)
[*data.columns]=["z1",'z2']

| | z1 | z2 | | ---: | ---- | ---- | | 0 | 16 | 13 | | 1 | 57 | 0 | | 2 | 36 | 16 | | 3 | 76 | 86 | | 4 | 88 | 64 | | 5 | 12 | 24 | | 6 | 86 | 59 | | 7 | 28 | 61 | | 8 | 44 | 29 | | 9 | 56 | 91 | | 10 | 5 | 4 |

data.sort_values(by="z1",ascending= False)

| | z1 | z2 | | ---: | ---- | ---- | | 4 | 88 | 64 | | 6 | 86 | 59 | | 3 | 76 | 86 | | 1 | 57 | 0 | | 9 | 56 | 91 | | 8 | 44 | 29 | | 2 | 36 | 16 | | 7 | 28 | 61 | | 0 | 16 | 13 | | 5 | 12 | 24 | | 10 | 5 | 4 |

data.sort_values(by="z2",ascending= False)

| | z1 | z2 | | ---: | ---- | ---- | | 9 | 56 | 91 | | 3 | 76 | 86 | | 4 | 88 | 64 | | 7 | 28 | 61 | | 6 | 86 | 59 | | 8 | 44 | 29 | | 5 | 12 | 24 | | 2 | 36 | 16 | | 0 | 16 | 13 | | 10 | 5 | 4 | | 1 | 57 | 0 |

import random
random.seed=1234
import pandas as pd
import numpy as np
#a=np.random.randint(low=0,high=100,size=(10,6))
data = pd.DataFrame(a)
data.apply(lambda x:x*10)
[*data.columns]=["z1",'z2',"z3",'z4',"z5",'z6']
data.sort_values(by=8,ascending= False,axis=1)

| | z3 | z4 | z1 | z2 | z5 | z6 | | ----: | ------ | ------ | ------ | ------ | ------ | ----- | | 0 | 89 | 63 | 65 | 45 | 61 | 84 | | 1 | 51 | 18 | 75 | 22 | 28 | 29 | | 2 | 44 | 64 | 18 | 13 | 51 | 81 | | 3 | 18 | 29 | 17 | 47 | 4 | 53 | | 4 | 93 | 85 | 15 | 83 | 29 | 70 | | 5 | 19 | 74 | 33 | 83 | 15 | 45 | | 6 | 76 | 66 | 53 | 21 | 35 | 48 | | 7 | 58 | 46 | 31 | 40 | 93 | 55 | | 8 | 95 | 93 | 87 | 54 | 11 | 7 | | 9 | 93 | 62 | 17 | 42 | 65 | 80 |

sort

sort(key,reverse)

這個是列表的方法

key:是排序的條件

reverse:表示是否逆序,默認(rèn)是從小到大,默認(rèn)為False

x = ['mmm', 'mm', 'mm', 'm' ]
x.sort(key = len)
print (x)
# out: ['m', 'mm', 'mm', 'mmm']
y = [3, 2, 8 ,0 , 1]
y.sort(reverse = True)
print (y) 
#[8, 3, 2, 1, 0]
#True為逆序排列,F(xiàn)alse為正序排列

sorted

對所有可迭代對象都可以排序。

而且不會改變原有的可迭代對象的結(jié)構(gòu),而是生成一個新的數(shù)據(jù)。

#sorted(L)返回一個排序后的L,不改變原始的L
L=[('b',2),('a',100),('c',30),('d',48)]
sorted(L, key=lambda x:x[1])
# out:
# [('b', 2), ('c', 30), ('d', 48), ('a', 100)]
sorted(L, key=lambda x:x[0])
# out:[('a', 100), ('b', 2), ('c', 30), ('d', 48)]

Enumerate

enumerate 是一個會返回元組迭代器的內(nèi)置函數(shù),這些元組包含列表的索引和值。當(dāng)你需要在循環(huán)中獲取可迭代對象的每個元素及其索引時,將經(jīng)常用到該函數(shù)。

示例代碼:

letters = ['a', 'b', 'c', 'd', 'e']
for i, letter in enumerate(letters):
 print(i, letter)

返回的結(jié)果

0 a
1 b
2 c
3 d
4 e
Python數(shù)據(jù)分析常用高階函數(shù)大全

練習(xí)題

Python 中的 Zip 和 Enumerate[相關(guān)練習(xí)]

使用 zip 寫一個 for 循環(huán),該循環(huán)會創(chuàng)建一個字符串,指定每個點(diǎn)的標(biāo)簽和坐標(biāo),并將其附加到列表 points。每個字符串的格式應(yīng)該為 label: x, y, z。例如,第一個坐標(biāo)的字符串應(yīng)該為 F: 23, 677, 4。

參考答案:

x_coord = [23, 53, 2, -12, 95, 103, 14, -5]
y_coord = [677, 233, 405, 433, 905, 376, 432, 445]
z_coord = [4, 16, -6, -42, 3, -6, 23, -1]
labels = ["F", "J", "A", "Q", "Y", "B", "W", "X"]
points = []
# write your for loop here
for label, x, y, z in zip(labels, x_coord, y_coord, z_coord):
 points.append(label+": " + str(x) + ', ' + str(y) + ', ' + str(z))
for point in points:
 print(point)

輸出如下:

F: 23, 677, 4 J: 53, 233, 16 A: 2, 405, -6 Q: -12, 433, -42 Y: 95, 905, 3 B: 103, 376, -6 W: 14, 432, 23 X: -5, 445, -1

使用 zip 創(chuàng)建一個字段 cast,該字典使用 names 作為鍵,并使用 heights 作為值。

參考答案:

cast_names = ["Barney", "Robin", "Ted", "Lily", "Marshall"]
cast_heights = [72, 68, 72, 66, 76]
cast = dict(zip(cast_names,cast_heights))
print(cast)

輸出:

{'Barney': 72, 'Ted': 72, 'Robin': 68, 'Lily': 66, 'Marshall': 76}

將 cast 元組拆封成兩個 names 和 heights 元組。

參考答案:

cast = (("Barney", 72), ("Robin", 68), ("Ted", 72), ("Lily", 66), ("Marshall", 76))
# define names and heights here
names,heights = zip(*cast)
print(names) # ('Barney', 'Robin', 'Ted', 'Lily', 'Marshall')
print(heights) # (72, 68, 72, 66, 76)

使用 zip 將 data 從 4x3 矩陣轉(zhuǎn)置成 3x4 矩陣。

參考答案:

data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11))
data_transpose = tuple(zip(*data))
print(data_transpose) # ((0, 3, 6, 9), (1, 4, 7, 10), (2, 5, 8, 11))

使用 enumerate 修改列表 cast,使每個元素都包含姓名,然后是角色的對應(yīng)身高。例如,cast 的第一個元素應(yīng)該從 “Barney Stinson” 更改為 "Barney Stinson 72”。

參考答案:

cast = ["Barney Stinson", "Robin Scherbatsky", "Ted Mosby", "Lily Aldrin", "Marshall Eriksen"]
heights = [72, 68, 72, 66, 76]
for i, c in enumerate(cast):
 cast[i] += ' ' + str(heights[i])
print(cast) # ['Barney Stinson 72', 'Robin Scherb

推導(dǎo)式

推導(dǎo)式comprehensions(又稱解析式),是Python的一種獨(dú)有特性。推導(dǎo)式是可以從一個數(shù)據(jù)序列構(gòu)建另一個新的數(shù)據(jù)序列的結(jié)構(gòu)體。 共有三種推導(dǎo),在Python2和3中都有支持:

  • 列表(list)推導(dǎo)式
  • 字典(dict)推導(dǎo)式
  • 集合(set)推導(dǎo)式

列表推導(dǎo)式

1、使用[]生成list

例一:

multiples = [i for i in range(20) if i % 5 is 0]
print(multiples)
# Output:[0, 5, 10, 15]

例二:

def sd(x):
 return x*x
multiples = [sd(i) for i in range(20) if i % 5 is 0]
print (multiples)
# Output: [0, 25, 100, 225]

字典推導(dǎo)式

字典推導(dǎo)和列表推導(dǎo)的使用方法是類似的,只不過中括號該改成大括號。直接舉例說明:

m = {'a': 200, 'b': 56}
ma = {v: k for k, v in m.items()}
print (ma)
# Output: {200: 'a', 56: 'b'}

集合推導(dǎo)式

它們跟列表推導(dǎo)式也是類似的。 唯一的區(qū)別在于它使用大括號{}。

例一:

squared = {x**2 for x in [1, 1, 2, 2]}
print(squared)
# Output: set([1, 4])

集合推導(dǎo)式有一個好處就是可以做到去重

collections模塊的Counter類

Python標(biāo)準(zhǔn)庫——collections模塊的Counter類

collections模塊包含了dict、set、list、tuple以外的一些特殊的容器類型,分別是:

  • OrderedDict類:排序字典,是字典的子類。
  • namedtuple()函數(shù):命名元組,是一個工廠函數(shù)。
  • Counter類:為hashable對象計數(shù),是字典的子類。
  • deque:雙向隊列。
  • defaultdict:使用工廠函數(shù)創(chuàng)建字典,使不用考慮缺失的字典鍵。
Python數(shù)據(jù)分析常用高階函數(shù)大全

Counter類

Counter類的目的是用來跟蹤值出現(xiàn)的次數(shù)。它是一個無序的容器類型,以字典的鍵值對形式存儲,其中元素作為key,其計數(shù)作為value。計數(shù)值可以是任意的Interger(包括0和負(fù)數(shù))。Counter類和其他語言的bags或multisets很相似。

創(chuàng)建

下面的代碼說明了Counter類創(chuàng)建的四種方法:

Counter類的創(chuàng)建

Python

c = Counter() # 創(chuàng)建一個空的Counter類

c = Counter('gallahad') # 從一個可iterable對象(list、tuple、dict、字符串等)創(chuàng)建>

c = Counter({'a': 4, 'b': 2}) # 從一個字典對象創(chuàng)建 c = Counter(a=4, b=2) # 從一組鍵值對創(chuàng)建

計數(shù)值的訪問與缺失的鍵

當(dāng)所訪問的鍵不存在時,返回0,而不是KeyError;否則返回它的計數(shù)。

計數(shù)值的訪問

c = Counter("abcdefgab")

c["a"] 2

c["c"] 1

c["h"] 0

計數(shù)器的更新(update和subtract)

可以使用一個iterable對象或者另一個Counter對象來更新鍵值。

計數(shù)器的更新包括增加和減少兩種。其中,增加使用update()方法:

計數(shù)器的更新(update)

c = Counter('which')

c.update('witch') # 使用另一個iterable對象更新

c['h']3

d = Counter('watch')

c.update(d) # 使用另一個Counter對象更新

c['h'] 4

減少則使用subtract()方法:

計數(shù)器的更新(subtract)

Python

c = Counter('which')

c.subtract('witch') # 使用另一個iterable對象更新

c['h']1

d = Counter('watch')

c.subtract(d) # 使用另一個Counter對象更新

c['a']-1

鍵的刪除

當(dāng)計數(shù)值為0時,并不意味著元素被刪除,刪除元素應(yīng)當(dāng)使用del。

鍵的刪除

Python

c = Counter("abcdcba")

c=Counter({'a': 2, 'c': 2, 'b': 2, 'd': 1})

c["b"] = 0

c=Counter({'a': 2, 'c': 2, 'd': 1, 'b': 0})

del c["a"]

c=Counter({'c': 2, 'b': 2, 'd': 1})

elements()

返回一個迭代器。元素被重復(fù)了多少次,在該迭代器中就包含多少個該元素。元素排列無確定順序,個數(shù)小于1的元素不被包含。

elements()方法

c = Counter(a=4, b=2, c=0, d=-2)

list(c.elements())['a', 'a', 'a', 'a', 'b', 'b']

most_common([n])

返回一個TopN列表。如果n沒有被指定,則返回所有元素。當(dāng)多個元素計數(shù)值相同時,排列是無確定順序的。

most_common()方法

Python

c = Counter('abracadabra')

c.most_common()[('a', 5), ('r', 2), ('b', 2), ('c', 1), ('d', 1)]

c.most_common(3)[('a', 5), ('r', 2), ('b', 2)]

淺拷貝copy

淺拷貝copy

Python

c = Counter("abcdcba")

cCounter({'a': 2, 'c': 2, 'b': 2, 'd': 1})

d = c.copy()>>> dCounter({'a': 2, 'c': 2, 'b': 2, 'd': 1})

算術(shù)和集合操作

+、-、&、|操作也可以用于Counter。其中&和|操作分別返回兩個Counter對象各元素的最小值和最大值。需要注意的是,得到的Counter對象將刪除小于1的元素。

Counter對象的算術(shù)和集合操作

Python

c = Counter(a=3, b=1)

d = Counter(a=1, b=2)

c + d # c[x] + d[x]Counter({'a': 4, 'b': 3})

c - d # subtract(只保留正數(shù)計數(shù)的元素)Counter({'a': 2}

c & d # 交集: min(c[x], d[x])Counter({'a': 1, 'b': 1})

c \| d # 并集: max(c[x], d[x])Counter({'a': 3, 'b': 2})

常用操作

下面是一些Counter類的常用操作,來源于Python官方文檔

Counter類常用操作

sum(c.values()) # 所有計數(shù)的總數(shù)

c.clear() # 重置Counter對象,注意不是刪除

list(c) # 將c中的鍵轉(zhuǎn)為列表

set(c) #將c中的鍵轉(zhuǎn)為set

dict(c) # 將c中的鍵值對轉(zhuǎn)為字典

c.items() # 轉(zhuǎn)為(elem, cnt)格式的列表

Counter(dict(list_of_pairs)) # 從(elem, cnt)格式的列表轉(zhuǎn)換為Counter類對象

c.most_common()[:-n:-1] # 取出計數(shù)最少的n-1個元素

c += Counter() # 移除0和負(fù)值

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時表示是新驗證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }