數據分析打工人常用NumPy 70個高頻操作(下篇)

2021-02-20 pythonic生物人
目錄
36、求numpy.ndarray兩列相關係數
37、判斷numpy.ndarray中是否有null值
38、使用指定值替代numpy.ndarray中的預設值
39、計算numpy.ndarray元素頻率
40、將numpy.ndarray元素由數值型轉換為分類型
41、由numpy.ndarray已知列得到新列
42、numpy.ndarray概率抽樣
43、numpy.ndarray按某個指標分類後求第二大的元素
44、通過numpy.ndarray某一列排序
45、挑選numpy.ndarray中頻數最高的元素
46、輸出numpy.ndarray中第一次大於給定元素的位置
47、使用給定值替換numpy.ndarray中滿足條件的元素
48、獲取numpy.ndarray中大小排前n的元素位置、元素
49、求numpy.ndarray的row wise counts
50、多個numpy.ndarray合成一個
51、計算numpy.ndarray的one-hot encodings numpy.ndarray
52、create row numbers grouped by a categorical variable
53、create groud ids based on a given categorical variable
54、numpy.ndarray(一維)元素rank
55、numpy.ndarray(多維)元素rank
56、輸出numpy.ndarray每行的最大元素
57、輸出numpy.ndarray每行的最小值與最大值比值
58、判斷numpy.ndarray中元素是否是第一次出現
59、求numpy.ndarray中每組元素的均值
60、將PIL image轉換為numpy.ndarray
61、丟棄numpy.ndarray中所有預設值
62、計算兩個numpy.ndarray的歐幾裡得距離
63、求numpy.ndarray的局部最大值位置
64、numpy.ndarray減法運算
65、輸出numpy.ndarray中元素第n次重複的位置
66、numpy.ndarray數據格式從datetime64轉換為datetime
67、計算numpy.ndarray數據窗口大小
68、指定起始、終止、步長,構建numpy.ndarray
69、補齊非連續時間序列numpy.ndarray
70、構建按指定步長滑窗的numpy.ndarray

36、求numpy.ndarray兩列相關係數
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])

#方法1
np.corrcoef(iris[:, 0], iris[:, 2])[0, 1]

#方法2
from scipy.stats.stats import pearsonr  
corr, p_value = pearsonr(iris[:, 0], iris[:, 2])
print(corr)

37、判斷numpy.ndarray中是否有null值
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])

np.isnan(iris_2d).any()

38、使用指定值替代numpy.ndarray中的預設值
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])
iris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)] = np.nan


iris_2d[np.isnan(iris_2d)] = 0#使用0替代預設值
iris_2d[:4]

39、計算numpy.ndarray元素頻率
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')
names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')

species = np.array([row.tolist()[4] for row in iris])

# Get the unique values and the counts
np.unique(species, return_counts=True)

40、將numpy.ndarray元素由數值型轉換為分類型
'''
需求:
Less than 3 --> 'small'
3-5 --> 'medium'
'>=5 --> 'large'
'''

url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')
names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')

# Bin petallength 
petal_length_bin = np.digitize(iris[:, 2].astype('float'), [0, 3, 5, 10])

# Map it to respective category
label_map = {1: 'small', 2: 'medium', 3: 'large', 4: np.nan}
petal_length_cat = [label_map[x] for x in petal_length_bin]

# View
petal_length_cat[:4]

41、由numpy.ndarray已知列得到新列
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='object')

#計算新列
sepallength = iris_2d[:, 0].astype('float')
petallength = iris_2d[:, 2].astype('float')
volume = (np.pi * petallength * (sepallength**2))/3

# 轉換為iris_2d大小
volume = volume[:, np.newaxis]

#添加新列
out = np.hstack([iris_2d, volume])
out[:4]

42、numpy.ndarray概率抽樣
#需求:抽樣結果使得species中setose is twice the number of versicolor and virginica
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')

# Get the species column
species = iris[:, 4]

#方法1
np.random.seed(100)
a = np.array(['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'])
species_out = np.random.choice(a, 150, p=[0.5, 0.25, 0.25])

#方法2
np.random.seed(100)
probs = np.r_[np.linspace(0, 0.500, num=50), np.linspace(0.501, .750, num=50), np.linspace(.751, 1.0, num=50)]
index = np.searchsorted(probs, np.random.random(150))
species_out = species[index]
print(np.unique(species_out, return_counts=True))

43、numpy.ndarray按某個指標分類後求第二大的元素
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')

# Get the species and petal length columns
petal_len_setosa = iris[iris[:, 4] == b'Iris-setosa', [2]].astype('float')

# Get the second last value
np.unique(np.sort(petal_len_setosa))[-2]

44、通過numpy.ndarray某一列排序
import numpy as np
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')
names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')
print(iris[iris[:,0].argsort()][:20])#按第一列排序

45、挑選numpy.ndarray中頻數最高的元素
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')

vals, counts = np.unique(iris[:, 2], return_counts=True)
print(vals[np.argmax(counts)])

46、輸出numpy.ndarray中第一次大於給定元素的位置
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')

np.argwhere(iris[:, 3].astype(float) > 1.0)[0]

47、使用給定值替換numpy.ndarray中滿足條件的元素
#需求:numpy.ndarray中大於30的用30替換、小於10的用10替換
np.set_printoptions(precision=2)
np.random.seed(100)
a = np.random.uniform(1,50, 20)

#方法1
np.clip(a, a_min=10, a_max=30)

#方法2
print(np.where(a < 10, 10, np.where(a > 30, 30, a)))

48、獲取numpy.ndarray中大小排前n的元素位置、元素
np.random.seed(100)
a = np.random.uniform(1,50, 20)

##獲取numpy.ndarray中大小排前5的元素位置
#方法1
print(a.argsort())

#方法2
np.argpartition(-a, 5)[:5]

##獲取numpy.ndarray中大小排前5的元素
#方法1
a[a.argsort()][-5:]

#方法2
np.sort(a)[-5:]

#方法3
np.partition(a, kth=-5)[-5:]

#方法4
a[np.argpartition(-a, 5)][:5]

49、求numpy.ndarray的row wise counts
np.random.seed(100)
arr = np.random.randint(1,11,size=(6, 10))
print(arr)
def counts_of_all_values_rowwise(arr2d):
    # Unique values and its counts row wise
    num_counts_array = [np.unique(row, return_counts=True) for row in arr2d]

    # Counts of all values row wise
    return([[int(b[a==i]) if i in a else 0 for i in np.unique(arr2d)] for a, b in num_counts_array])

print(np.arange(1,11))
counts_of_all_values_rowwise(arr)

50、多個numpy.ndarray合成一個
arr1 = np.arange(3)
arr2 = np.arange(3,7)
arr3 = np.arange(7,10)

array_of_arrays = np.array([arr1, arr2, arr3])
print('array_of_arrays: ', array_of_arrays)

#方法
arr_2d = np.array([a for arr in array_of_arrays for a in arr])

#方法2
arr_2d = np.concatenate(array_of_arrays)
print(arr_2d)

51、計算numpy.ndarray的one-hot encodings numpy.ndarray
np.random.seed(101) 
arr = np.random.randint(1,4, size=6)
arr
print(arr)

# Solution:
def one_hot_encodings(arr):
    uniqs = np.unique(arr)
    out = np.zeros((arr.shape[0], uniqs.shape[0]))
    for i, k in enumerate(arr):
        out[i, k-1] = 1
    return out

one_hot_encodings(arr)

52、create row numbers grouped by a categorical variable
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
species = np.genfromtxt(url, delimiter=',', dtype='str', usecols=4)
np.random.seed(100)
species_small = np.sort(np.random.choice(species, size=20))
print(species_small)

print([i for val in np.unique(species_small) for i, grp in enumerate(species_small[species_small==val])])

53、create groud ids based on a given categorical variable
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
species = np.genfromtxt(url, delimiter=',', dtype='str', usecols=4)
np.random.seed(100)
species_small = np.sort(np.random.choice(species, size=20))
print(species_small)
output = [np.argwhere(np.unique(species_small) == s).tolist()[0][0] for val in np.unique(species_small) for s in species_small[species_small==val]]
output

54、numpy.ndarray(一維)元素rank
np.random.seed(10)
a = np.random.randint(20, size=10)
print('Array: ', a)


print(a.argsort().argsort())

55、numpy.ndarray(多維)元素rank
np.random.seed(10)
a = np.random.randint(20, size=[2,5])
print(a)

print(a.ravel().argsort().argsort().reshape(a.shape))

56、輸出numpy.ndarray每行的最大元素
np.random.seed(100)
a = np.random.randint(1,10, [5,3])
print(a)

# 方法1
np.amax(a, axis=1)

#方法2
np.apply_along_axis(np.max, arr=a, axis=1)

57、輸出numpy.ndarray每行的最小值與最大值比值
np.random.seed(100)
a = np.random.randint(1,10, [5,3])
print(a)

np.apply_along_axis(lambda x: np.min(x)/np.max(x), arr=a, axis=1)

58、判斷numpy.ndarray中元素是否是第一次出現
np.random.seed(100)
a = np.random.randint(0, 5, 10)

# There is no direct function to do this as of 1.13.3

# Create an all True array
out = np.full(a.shape[0], True)

# Find the index positions of unique elements
unique_positions = np.unique(a, return_index=True)[1]

# Mark those positions as False
out[unique_positions] = False

print(out)

59、求numpy.ndarray中每組元素的均值
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')
names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')


# No direct way to implement this. Just a version of a workaround.
numeric_column = iris[:, 1].astype('float')  # sepalwidth
grouping_column = iris[:, 4]  # species

# List comprehension version
[[group_val, numeric_column[grouping_column==group_val].mean()] for group_val in np.unique(grouping_column)]

# For Loop version
output = []
for group_val in np.unique(grouping_column):
    output.append([group_val, numeric_column[grouping_column==group_val].mean()])

output

60、將PIL image轉換為numpy.ndarray
from io import BytesIO
from PIL import Image
import PIL, requests

# Import image from URL
URL = 'https://upload.wikimedia.org/wikipedia/commons/8/8b/Denali_Mt_McKinley.jpg'
response = requests.get(URL)

# Read it as Image
I = Image.open(BytesIO(response.content))

# Optionally resize
I = I.resize([150,150])

# Convert to numpy array
arr = np.asarray(I)

# Optionaly Convert it back to an image and show
im = PIL.Image.fromarray(np.uint8(arr))
Image.Image.show(im)

61、丟棄numpy.ndarray中所有預設值
a = np.array([1,2,3,np.nan,5,6,7,np.nan])
print(a)
a[~np.isnan(a)]

62、計算兩個numpy.ndarray的歐幾裡得距離
a = np.array([1,2,3,4,5])
b = np.array([4,5,6,7,8])

# Solution
dist = np.linalg.norm(a-b)
dist

63、求numpy.ndarray的局部最大值位置
a = np.array([1, 3, 7, 1, 2, 6, 0, 1])
doublediff = np.diff(np.sign(np.diff(a)))
peak_locations = np.where(doublediff == -2)[0] + 1
peak_locations

64、numpy.ndarray減法運算
#需求:Subtract the 1d array b_1d from the 2d array a_2d, such that each item of b_1d subtracts from respective row of a_2d.
a_2d = np.array([[3,3,3],[4,4,4],[5,5,5]])
b_1d = np.array([1,2,3])

print(a_2d - b_1d[:,None])

65、輸出numpy.ndarray中元素第n次重複的位置
x = np.array([1, 2, 1, 1, 3, 4, 3, 1, 1, 2, 1, 1, 2])
print(x)
n = 5

#方法1:列表推導式
[i for i, v in enumerate(x) if v == 1][n-1]#輸出元素1第5次重複的位置

#方法2
np.where(x == 1)[0][n-1]

66、numpy.ndarray數據格式從datetime64轉換為datetime
dt64 = np.datetime64('2018-02-25 22:10:10')

#方法1
from datetime import datetime
dt64.tolist()


#方法2
dt64.astype(datetime)

67、計算numpy.ndarray數據窗口大小
def moving_average(a, n=3) :
    ret = np.cumsum(a, dtype=float)
    ret[n:] = ret[n:] - ret[:-n]
    return ret[n - 1:] / n

np.random.seed(100)
Z = np.random.randint(10, size=10)
print('array: ', Z)

#方法1
moving_average(Z, n=3).round(2)

#方法2
np.convolve(Z, np.ones(3)/3, mode='valid')  

68、指定起始、終止、步長,構建numpy.ndarray
length = 10
start = 5
step = 3

def seq(start, length, step):
    end = start + (step*length)
    return np.arange(start, end, step)

seq(start, length, step)

69、補齊非連續時間序列numpy.ndarray
dates = np.arange(np.datetime64('2018-02-01'), np.datetime64('2018-02-25'), 2)
print(dates)

#方法1
filled_in = np.array([
    np.arange(date, (date + d)) for date, d in zip(dates, np.diff(dates))
]).reshape(-1)

output = np.hstack([filled_in, dates[-1]])
output

#方法2
out = []
for date, d in zip(dates, np.diff(dates)):
    out.append(np.arange(date, (date + d)))

filled_in = np.array(out).reshape(-1)
output = np.hstack([filled_in, dates[-1]])
output

70、構建按指定步長滑窗的numpy.ndarray
import numpy as np


def gen_strides(a, stride_len=5, window_len=5):
    n_strides = ((a.size - window_len) // stride_len) + 1
    # return np.array([a[s:(s+window_len)] for s in np.arange(0, a.size, stride_len)[:n_strides]])
    return np.array([
        a[s:(s + window_len)]
        for s in np.arange(0, n_strides * stride_len, stride_len)
    ])


print(gen_strides(np.arange(15), stride_len=2, window_len=4))

相關焦點

  • 數據分析打工人常用NumPy 70個高頻操作(上篇)
    中滿足某個條件的元素15、定義函數操作numpy.ndarray中元素16、改變numpy.ndarray中兩列順序17、改變numpy.ndarray中兩行順序18、顛倒numpy.ndarray中各行順序 19、顛倒numpy.ndarray中各列順序20、創建一個包含隨機浮點數的numpy.ndarray21、numpy.ndarray中所有元素保留三位小數
  • Python數據分析 - Numpy
    如今,np被Python其它科學計算包作為基礎包,已成為Python 數據分析的基礎,可以說,NP是SciPy、Pandas等數據處理或科學計算庫最基本的函數功能庫。因此,理解np的數據類型對python數據分析十分有幫助。下面,本文將介紹Np的常用操作和基本數據類型。NP提供了以下重點功能。
  • 【數據分析】Numpy
    Numpy是高性能科學計算和數據分析的基礎包。它也是pandas等其他數據分析的工具的基礎,基本所有數據分析的包都用過它。它將常用的數學函數都支持向量化運算,使得這些數學函數能夠直接對數組進行操作,將本來需要在Python級別進行的循環,放到C語言的運算中,明顯地提高了程序的運算速度。
  • Python 數據分析:Numpy 介紹
    如今,np被Python其它科學計算包作為基礎包,已成為Python 數據分析的基礎,可以說,NP是SciPy、Pandas等數據處理或科學計算庫最基本的函數功能庫。因此,理解np的數據類型對python數據分析十分有幫助。下面,本文將介紹Np的常用操作和基本數據類型。NP提供了以下重點功能。
  • Python 數據分析:NumPy 基礎知識
    )常用屬性通過示例來看一下 ndarray 對象的常用屬性import numpy as nparr = np.array([1, 2, 3])# 元素類型print(arr.dtype= np.arange(30)print(arr)# 變成二維數組arr.shape = (5, 6)print(arr)# 變成三維數組arr = arr.reshape((2, 3, 5))print(arr)2.2 數據類型通過下表來看一下 NumPy 的常用數據類型。
  • python數據分析專題 (9):numpy基礎
    NumPy(Numerical Python的簡稱)是高性能科學計算和數據分析的基礎包。NumPy最重要的一個特點就是其N維數組對象(即ndarray),該對象是一個快速而靈活的大數據集容器。新手可能不理解這句話的含義,這個需要慢慢去理解 。總之,知道numpy是python數據分析最重要的基礎包就可以了。
  • 學員筆記||Python數據分析之:numpy入門(一)
    (點擊上方公眾號,快速關注一起學AI)這是我學<Python數據分析>時整理出來的numpy基礎速讀筆記,內容大致分為
  • Python|Numpy的常用操作
    import numpy as nplist1 = [1.1, 2.2, 3, 4, 5]nd1 = np.array(list1)print(type(nd1))print(list1)list2 = [[1.1, 2.2, 3, 4, 5],[7.7, 8.8, 9, 10, 11]]nd2 = np.array
  • 從零開始學Python數據分析【4】-- numpy
    # 浮點型的最小值np.fmin# 求和np.sum# 均值np.mean# 標準差np.std# 方差np.var# 中位數np.median映射函數>apply_along_axisapply_along_axis函數與R語言中的apply函數用法一致,可以針對某個軸的方向進行函數操作,同樣,而且在pandas模塊中的DataFrmae對象中,可以使用apply函數
  • Excel和Python常用功能的操作(數據分析)
    Excel與Python都是數據分析中常用的工具,本文介紹這兩種工具是如何實現數據的讀取、生成、計算、修改、統計、抽樣、查找、可視化、存儲等數據處理中的常用操作!Python:通過導入pandas庫,使用 pandas.read_excel("filepath")打開隨機生成數據Excel:拉取一定範圍後,上方輸入公式RAND()Python:導入numpy庫,np.DataFrame(np.random.rand
  • NumPy:創建和操作數值數據
    不同的數據類型可以更緊湊的在內存中存儲數據,但是大多數時候我們都只是操作浮點數據。注意,在上面的例子中,Numpy自動從輸入中識別了數據類型。1.3.3 數據的更多內容1.3.3.1 更多的數據類型1.3.3.1.1 投射「更大」的類型在混合類型操作中勝出:In [175]:np.array([1, 2, 3]) + 1.5Out[175]:array([ 2.5, 3.5, 4.5])賦值不會改變類型!
  • 每個數據科學家都應該知道的20個NumPy操作
    關於數據科學的一切都始於數據,數據以各種形式出現。數字、圖像、文本、x射線、聲音和視頻記錄只是數據源的一些例子。無論數據採用何種格式,都需要將其轉換為一組待分析的數字。因此,有效地存儲和修改數字數組在數據科學中至關重要。
  • Python數據分析基礎之NumPy學習 (上)
    如果元素全是數值型變量 (numerical variable),那麼 numpy 數組明顯是個很好的數據結構。學習 numpy 還是遵循的 Python 裡「萬物皆對象」的原則,既然把數組當對象,我們就按著數組的創建、數組的存載、數組的獲取、數組的變形、和數組的計算來盤一盤 NumPy,目錄如下:
  • numpy中數組操作的相關函數
    ,就是說,先對原始數據進行拷貝,生成一個新的數組,新的數組和原始數組是獨立的,對副本的操作並不會影響到原始數組;視圖是一個數組的引用,對引用進行操作,也就是對原始數據進行操作,所以修改視圖會對應的修改原始數組。
  • Python數據分析之numpy學習(一)
    在學完《廖雪峰Python2.7教程》感覺受益匪淺,掌握了基本的語法之後開始接觸用Python進行數據分析。這裡向大家推薦兩本書《Python數據分析》和《利用Python進行數據分析》,而這兩本書也是目前我正在學習的材料,雖然這兩本書都是基於Python2.x,但對於Python3.x也能正常運行。
  • 從numpy開啟Python數據科學之旅
    一個路徑就是從純程式語言的角度來學習Python的,包括Python編程基礎、編寫函數、Python高級特性、函數式編程、面向對象編程、多進程和多線程、常用內建模塊和第三方庫等等,旨在學習和鍛鍊編程思維,提高小編自身的coding能力。
  • Python數據分析之Numpy學習 2——NumPy 基礎 ndarray對象
    Python數據分析之Numpy學習 2 —— NumPy 基礎學習NumPy(Numerical Python)是高性能科學計算和數據分析的基礎包。NumPy的主要對象是同構數據多維容器(homogeneous multidimensional array)——ndarray,也就是說每一個ndarray都是一個相同類型元素組成的表格(二維)。在NumPy中維度(dimensions)叫做軸(axes),軸的個數叫做秩(rank)。軸這個概念必須牢記,否則放棄吧。首先軸是從0開始計的,0代表最高維,次高維是1,以此類推。
  • 再見Numpy,Pandas!又一個數據分析神器橫空出現!
    ,想必大家都或多或少的有一定的了解,常見的像是numpy和pandas更是大家日常使用的數據分析工具。但是面對大數據的處理時,像是numpy和pandas的在加載數據時,會看到內存用量的飆升,而dask卻可以將這些大的數據進行並行計算。今天小編就帶領大家學習一個並行的計算庫——dask。
  • python數據分析:numpy入門
    微信公眾號:學點啥玩點啥小白友好型python數據分析:numpy入門numpy:一個在python中做科學計算的基礎庫,重在數值計算,也是大部分python科學計算庫的基礎庫,多用於在大型、多維數組上執行數值計算。
  • 數據分析-numpy庫快速了解
    NumPy是SciPy、Pandas等數據處理或科學計算庫的基礎2.numpy庫有什麼用numpy用途是很廣的,涉及到數字計算等都可以使用,它的優勢在於底層是C語言開發的數據非常快。 數組對象可以去掉元素間運算所需的循環,使一維向量更像單個數據 設置專門的數組對象,經過優化,可以提升這類應用的運算速度觀察:科學計算中,一個維度所有數據的類型往往相同 數組對象採用相同的數據類型,有助於節省運算和存儲空間具體可以看下面一個例子:(來源嵩天老師案例)3.numpy庫怎麼使用先安裝numpy