簡體   English   中英

使用操作從 Python 列表創建 numpy 數組

[英]Create numpy array from Python list with operations

我在 Python 列表中有數據,我從數據庫(sqlite)中提取以下格式的數據:

# This is an example
data = [(1, '12345', 1, 0, None), (1, '34567', 1, 1, None)]

從這個元組列表中,我想創建一個二維 numpy 數組,將每個元組轉換為一個數組。 在這樣做的同時,我還希望能夠指定數據的轉換。 具體來說,我希望將元組中索引 1 處的值從字符串轉換為數字,如果沒有,則將最后一個索引處的值轉換為 0,否則轉換為 1。

以下是示例數據之后的樣子:

transformed_data = np.asarray([[1, 12345, 1, 0, 0], [1, 34567, 1, 1, 0]])

我可以使用簡單的 for 循環來做到這一點,但是我想知道是否有更“Pythony”的解決方案,或者使用原生 numpy 方法或其他方法。 我正在使用一個非常大的數據庫,因此復雜性很重要。 提前致謝。

非常擅長:

import pandas as pd
                      # set up DataFrame
transformed_data = (pd.DataFrame(data)
                      # convert to numeric
                      .apply(pd.to_numeric, errors='coerce')
                      # replace null with 0
                      # trying to cast as integer if possible
                      .fillna(0, downcast='infer')
                      # convert to numpy array
                      .to_numpy()
                   )

output:

array([[    1, 12345,     1,     0,     0],
       [    1, 34567,     1,     1,     0]])

如果您的元組很小且大小固定,則可以使用列表推導:

result = [(a, int(b), c, d, 0 if e is None else e) for a, b, c, d, e in data]

或者更短一點:

result = [(d[0], int(d[1]), *d[2:4], d[4] if d[4] else 0) for d in data]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM