<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          每個(gè)數(shù)據(jù)科學(xué)家都應(yīng)該知道的12個(gè)Python特性!

          共 9500字,需瀏覽 19分鐘

           ·

          2023-08-09 03:06

             
          來源:大數(shù)據(jù)應(yīng)用

          本文約5700字,建議閱讀11分鐘

          本文我們將深入探討每個(gè)數(shù)據(jù)科學(xué)家都應(yīng)該了解的12個(gè)Python特性。


          圖片來源:carbon

          作為一名數(shù)據(jù)科學(xué)家,你對Python的強(qiáng)大功能并不陌生。從數(shù)據(jù)整理到機(jī)器學(xué)習(xí),Python已成為數(shù)據(jù)科學(xué)事實(shí)上的語言。但是你是否利用了Python提供的所有特性?

          在本文中,我們將深入探討每個(gè)數(shù)據(jù)科學(xué)家都應(yīng)該了解的12個(gè)Python特性。從推導(dǎo)式到數(shù)據(jù)類,這些特性將幫助你編寫更高效、可讀且可維護(hù)的代碼。

          01 推導(dǎo)

          Python中的推導(dǎo)式是機(jī)器學(xué)習(xí)和數(shù)據(jù)科學(xué)任務(wù)的有用工具,因?yàn)樗鼈冊试S以簡潔且可讀的方式創(chuàng)建復(fù)雜的數(shù)據(jù)結(jié)構(gòu)。

          列表推導(dǎo)式可用于生成數(shù)據(jù)列表,例如從一系列數(shù)字中創(chuàng)建平方值列表。嵌套列表推導(dǎo)式可用于平面化多維數(shù)組,這是數(shù)據(jù)科學(xué)中常見的預(yù)處理任務(wù)。


          # list comprehension_list = [x**2 for x in range(1, 11)]
          # nested list comprehension to flatten listmatrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
          flat_list = [num # append to list            for row in matrix # outer loop            for num in row] # inner loop
          print(_list)print(flat_list)[1, 4, 9, 16, 25, 36, 49, 64, 81, 100][1, 2, 3, 4, 5, 6, 7, 8, 9]


          字典和集合推導(dǎo)式分別用于創(chuàng)建字典和數(shù)據(jù)集。例如,字典推導(dǎo)可用于在機(jī)器學(xué)習(xí)模型中創(chuàng)建特征名稱及其相應(yīng)值的字典。

          生成器推導(dǎo)式對于處理大型數(shù)據(jù)集特別有用,因?yàn)樗鼈儎?dòng)態(tài)生成值,而不是在內(nèi)存中創(chuàng)建大型數(shù)據(jù)結(jié)構(gòu)。這有助于提高性能并減少內(nèi)存使用。


          # dictionary comprehension_dict = {var:var ** 2 for var in range(1, 11) if var % 2 != 0}
          # set comprehension# create a set of squares of numbers from 1 to 10_set = {x**2 for x in range(1, 11)}
          # generator comprehension_gen = (x**2 for x in range(1, 11))
          print(_dict)print(_set)print(list(g for g in _gen)){1: 1, 3: 9, 5: 25, 7: 49, 9: 81}{64, 1, 4, 36, 100, 9, 16, 49, 81, 25}[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


          02 枚舉

          enumerate是一個(gè)內(nèi)置函數(shù),允許迭代序列(例如列表或元組),同時(shí)跟蹤每個(gè)元素的索引。

          這在處理數(shù)據(jù)集時(shí)非常有用,因?yàn)樗试S輕松訪問和操作單個(gè)元素,同時(shí)跟蹤其索引位置。

          這里我們用enumerate迭代字符串列表,如果索引是偶數(shù)則打印出該值。



          for idx, value in enumerate(["a", "b", "c", "d"]):    if idx % 2 == 0:        print(value)ac


          03 Zip

          zip是一個(gè)內(nèi)置函數(shù),允許并行迭代多個(gè)序列(例如列表或元組)。

          下面我們使用zip同時(shí)迭代兩個(gè)列表x和y并對其相應(yīng)的元素執(zhí)行操作。


          x = [1, 2, 3, 4]y = [5, 6, 7, 8]
          # iterate over both arrays simultaneouslyfor a, b in zip(x, y):    print(a, b, a + b, a * b)1 5 6 52 6 8 123 7 10 214 8 12 32

          在本例中,它打印出和中每個(gè)元素的值x和y,它們的總和以及它們的乘積。

          04 生成器

          Python中的生成器是一種可迭代類型,它允許動(dòng)態(tài)生成一系列值,而不是一次生成所有值并將它們存儲(chǔ)在內(nèi)存中。

          這使得它們對于處理無法放入內(nèi)存的大型數(shù)據(jù)集非常有用,因?yàn)閿?shù)據(jù)是小塊或批量處理的,而不是一次性處理的。

          下面我們使用生成器函數(shù)來生成Fibonacci數(shù)列中的第一個(gè)數(shù)字n。該yield關(guān)鍵字用于一次生成序列中的每個(gè)值,而不是一次生成整個(gè)序列。


          def fib_gen(n):    a, b = 0, 1    for _ in range(n):        yield a        a, b = b, a + b

          res = fib_gen(10)print(list(r for r in res))[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]


          05 Lambda函數(shù)

          lambda是用于創(chuàng)建匿名函數(shù)的關(guān)鍵字,匿名函數(shù)是沒有名稱并且可以在一行代碼中定義的函數(shù)。

          它們對于動(dòng)態(tài)定義自定義函數(shù)以進(jìn)行特征工程、數(shù)據(jù)預(yù)處理或模型評估非常有用。

          下面我們lambda創(chuàng)建一個(gè)簡單的函數(shù)來從數(shù)字列表中過濾偶數(shù)。


          numbers = range(10)even_numbers = list(filter(lambda x: x % 2 == 0, numbers))print(even_numbers)[0, 2, 4, 6, 8]

          這是在Pandas中使用lambda函數(shù)的另一個(gè)代碼片段。


          import pandas as pd
          data = {    "sales_person": ["Alice", "Bob", "Charlie", "David"],    "sale_amount": [100, 200, 300, 400],}df = pd.DataFrame(data)
          threshold = 250df["above_threshold"] = df["sale_amount"].apply(    lambda x: True if x >= threshold else False)dfsales_person   sale_amount   above_threshold0   Alice   100   False1   Bob   200   False2   Charlie   300   True3   David   400   True


          06 映射、過濾、歸約

          函數(shù)map、filter和reduce是三個(gè)用于操作和轉(zhuǎn)換數(shù)據(jù)的內(nèi)置函數(shù)。

          map用于將函數(shù)應(yīng)用于可迭代的每個(gè)元素,filter用于根據(jù)條件從可迭代中選擇元素,reduce用于將函數(shù)應(yīng)用于迭代中的成對元素以產(chǎn)生單個(gè)結(jié)果。

          下面是一個(gè)綜合應(yīng)用三個(gè)函數(shù)的例子,計(jì)算偶數(shù)的平方和。


          numbers = range(10)
          # Use map(), filter(), and reduce() to preprocess and aggregate the list of numberseven_numbers = filter(lambda x: x % 2 == 0, numbers)squares = map(lambda x: x**2, even_numbers)sum_of_squares = reduce(lambda x, y: x + y, squares)

          print(f"Sum of the squares of even numbers: {sum_of_squares}")Sum of the squares of even numbers: 120


          07 any和all

          any和all是內(nèi)置函數(shù),允許檢查可迭代中的任何或所有元素是否滿足特定條件。

          any和all可用于檢查數(shù)據(jù)集或數(shù)據(jù)集子集是否滿足某些條件。例如,它們可用于檢查列中是否缺少任何值,或者列中的所有值是否在特定范圍內(nèi)。

          下面是檢查是否存在偶數(shù)值和所有奇數(shù)值的簡單示例。


          data = [1, 3, 5, 7]print(any(x % 2 == 0 for x in data))print(all(x % 2 == 1 for x in data))FalseTrue


          08 next

          next用于從迭代器中檢索下一個(gè)項(xiàng)目。迭代器是可以迭代(循環(huán))的對象,例如列表、元組、集合或字典。

          next在數(shù)據(jù)科學(xué)中通常用于迭代迭代器或生成器對象。它允許用戶從可迭代中檢索下一個(gè)項(xiàng)目,并且對于處理大型數(shù)據(jù)集或流數(shù)據(jù)非常有用。

          下面,我們定義一個(gè)生成器random_numbers(),生成0到1之間的隨機(jī)數(shù)。然后,我們使用next()函數(shù)查找生成器中第一個(gè)大于0.9的數(shù)字。


          import random 
          def random_numbers():    while True:        yield random.random()
          # Use next() to find the first number greater than 0.9num = next(x for x in random_numbers() if x > 0.9)
          print(f"First number greater than 0.9: {num}")First number greater than 0.9: 0.9444805819267413


          09 默認(rèn)字典


          defaultdict是內(nèi)置類的子類dict,允許為缺失的鍵提供默認(rèn)值。


          defaultdict對于處理丟失或不完整的數(shù)據(jù)非常有用,例如在處理稀疏

          矩陣或特征向量時(shí)。它還可用于計(jì)算分類變量的頻率。


          一個(gè)例子是計(jì)算列表中項(xiàng)目的出現(xiàn)次數(shù)。如果傳入default_factory的參數(shù)為int,一開始初始化鍵對應(yīng)的值都為0。


          from collections import defaultdict
          count = defaultdict(int)for item in ['a', 'b', 'a', 'c', 'b', 'a']:    count[item] += 1
          countdefaultdict(int, {'a': 3, 'b': 2, 'c': 1})


          10 partial

          partial是functools模塊中的一個(gè)函數(shù),它允許從預(yù)先填充了某些參數(shù)的現(xiàn)有函數(shù)創(chuàng)建新函數(shù)。

          partial對于創(chuàng)建帶有預(yù)先填充的特定參數(shù)或參數(shù)的自定義函數(shù)或數(shù)據(jù)轉(zhuǎn)換非常有用。這有助于減少定義和調(diào)用函數(shù)時(shí)所需的樣板代碼量。

          在這里,我們使用partial現(xiàn)有函數(shù)add創(chuàng)建一個(gè)新函數(shù)increment,并將其參數(shù)之一固定為值1。

          調(diào)用increment(1)本質(zhì)上就是調(diào)用add(1, 1)


          from functools import partial
          def add(x, y):    return x + y
          increment = partial(add, 1)increment(1)2


          11 lru_cache


          lru_cache是functools模塊中的一個(gè)修飾函數(shù),它允許使用有限大小的緩存來緩存函數(shù)的結(jié)果。


          lru_cache對于優(yōu)化計(jì)算成本較高的函數(shù)或可能使用相同參數(shù)多次調(diào)用的模型訓(xùn)練過程非常有用。


          緩存可以幫助加快函數(shù)的執(zhí)行速度并降低總體計(jì)算成本。


          這是一個(gè)使用緩存有效計(jì)算Fibonacci numbers(https://en.wikipedia.org/wiki/Fibonacci_number)的示例(在計(jì)算機(jī)科學(xué)中稱為記憶)


          rom functools import lru_cache
          @lru_cache(maxsize=None)def fibonacci(n):    if n <= 1:        return n    return fibonacci(n - 1) + fibonacci(n - 2)
          fibonacci(1e3)4.346655768693743e+208


          12 數(shù)據(jù)類

          @dataclass修飾器根據(jù)定義的屬性自動(dòng)類生成幾個(gè)特殊方法,例如__init__,__repr__,和__eq__。

          這有助于減少定義類時(shí)所需的樣板代碼量。dataclass對象可以表示數(shù)據(jù)點(diǎn)、特征向量或模型參數(shù)等。

          在此示例中,dataclass用于定義Person具有三個(gè)屬性的簡單類:name、age和city。


          from dataclasses import dataclass
          @dataclassclass Person:    name: str    age: int    city: str
          p = Person("Alice", 30, "New York")print(p)Person(name='Alice', age=30, city='New York')



          原文鏈接:
          https://medium.com/bitgrit-data-science-publication/12-python-features-every-data-scientist-should-know-1d233dbaab0c

          編輯:王菁

          瀏覽 1920
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評論
          圖片
          表情
          推薦
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  黄色视频网站在线观看免费 | 日本在线中文不卡 | 亲子伦A片免费 | 青青激情视频 | 超碰成人人人操 |