簡體   English   中英

將 numpy.array 存儲在 Pandas.DataFrame 的單元格中

[英]Store numpy.array in cells of a Pandas.DataFrame

我有一個 dataframe ,我想在其中存儲“原始” numpy.array

df['COL_ARRAY'] = df.apply(lambda r: np.array(do_something_with_r), axis=1)

但似乎pandas試圖“解壓”numpy.array。

有解決方法嗎? 除了使用包裝器(見下面的編輯)?

我試過reduce=False但沒有成功。

編輯

這行得通,但我必須使用“虛擬” Data class 來環繞數組,這是不令人滿意的,也不是很優雅。

class Data:
    def __init__(self, v):
        self.v = v

meas = pd.read_excel(DATA_FILE)
meas['DATA'] = meas.apply(
    lambda r: Data(np.array(pd.read_csv(r['filename'])))),
    axis=1
)

在 numpy 數組周圍使用包裝器,即將 numpy 數組作為列表傳遞

a = np.array([5, 6, 7, 8])
df = pd.DataFrame({"a": [a]})

輸出:

a
0  [5, 6, 7, 8]

或者您可以通過創建元組來使用apply(np.array) ,即如果您有數據框

df = pd.DataFrame({'id': [1, 2, 3, 4],
                   'a': ['on', 'on', 'off', 'off'],
                   'b': ['on', 'off', 'on', 'off']})

df['new'] = df.apply(lambda r: tuple(r), axis=1).apply(np.array)

輸出:

a    b  id            new
0   on   on   1    [on, on, 1]
1   on  off   2   [on, off, 2]
2  off   on   3   [off, on, 3]
3  off  off   4  [off, off, 4]
df['new'][0]

輸出:

array(['on', 'on', '1'], dtype='<U2')

如果您首先將列設置為object類型,則可以插入一個數組而無需任何換行:

df = pd.DataFrame(columns=[1])
df[1] = df[1].astype(object)
df.loc[1, 1] = np.array([5, 6, 7, 8])
df

輸出:

    1
1   [5, 6, 7, 8]

您可以將 Data Frame 數據參數包裝在方括號中以維護每個單元格中的np.array

one_d_array = np.array([1,2,3])
two_d_array = one_d_array*one_d_array[:,np.newaxis]
two_d_array

array([[1, 2, 3],
       [2, 4, 6],
       [3, 6, 9]])


pd.DataFrame([
    [one_d_array],
    [two_d_array] ])

                                   0
0                          [1, 2, 3]
1  [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

假設您有一個 DataFrame ds並且它有一個名為“class”的列。 如果ds ['class'] 包含字符串或數字,並且您想使用numpy.ndarraylist更改它們,則以下代碼會有所幫助。 在代碼中, class2vector是一個numpy.ndarraylistds_class是一個過濾條件。

ds['class'] = ds['class'].map(lambda x: class2vector if (isinstance(x, str) and (x == ds_class)) else x)

選擇eval buildin function 易於使用且易於閱讀。

# First ensure use object store str
df['col2'] = self.df['col2'].astype(object)
# read
arr_obj = eval(df.at[df[df.col_1=='xyz'].index[0], 'col2']))
# write
df.at[df[df.col_1=='xyz'].index[0], 'col2'] = str(arr_obj)

真實商店展示完美的人類可讀價值:

col_1,  col_2
xyz,    "['aaa', 'bbb', 'ccc', 'ddd']"

只需通過第一個apply將您想要存儲在一個單元格中的內容包裝到一個list對象中,然后通過第二個apply將該listindex 0提取出來:

import pandas as pd
import numpy as np

df = pd.DataFrame({'id': [1, 2, 3, 4],
                   'a': ['on', 'on', 'off', 'off'],
                   'b': ['on', 'off', 'on', 'off']})


df['new'] = df.apply(lambda x: [np.array(x)], axis=1).apply(lambda x: x[0])

df

輸出:

    id  a       b       new
0   1   on      on      [1, on, on]
1   2   on      off     [2, on, off]
2   3   off     on      [3, off, on]
3   4   off     off     [4, off, off]

這是我的 2 美分貢獻(在 Python 3.7 上測試):

import pandas as pd
import numpy as np

dataArray = np.array([0.0, 1.0, 2.0])
df = pd.DataFrame()
df['User Col A'] = [1]
df['Array'] = [dataArray]

暫無
暫無

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

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