简体   繁体   English

将 numpy.array 存储在 Pandas.DataFrame 的单元格中

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

I have a dataframe in which I would like to store 'raw' numpy.array :我有一个 dataframe ,我想在其中存储“原始” numpy.array

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

but it seems that pandas tries to 'unpack' the numpy.array.但似乎pandas试图“解压”numpy.array。

Is there a workaround?有解决方法吗? Other than using a wrapper (see edit below)?除了使用包装器(见下面的编辑)?

I tried reduce=False with no success.我试过reduce=False但没有成功。

EDIT编辑

This works, but I have to use the 'dummy' Data class to wrap around the array, which is unsatisfactory and not very elegant.这行得通,但我必须使用“虚拟” 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
)

Use a wrapper around the numpy array ie pass the numpy array as list在 numpy 数组周围使用包装器,即将 numpy 数组作为列表传递

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

Output:输出:

a
0  [5, 6, 7, 8]

Or you can use apply(np.array) by creating the tuples ie if you have a dataframe或者您可以通过创建元组来使用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)

Output :输出:

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]

Output :输出:

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

If you first set a column to have type object , you can insert an array without any wrapping:如果您首先将列设置为object类型,则可以插入一个数组而无需任何换行:

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

Output:输出:

    1
1   [5, 6, 7, 8]

You can wrap the Data Frame data args in square brackets to maintain the np.array in each cell:您可以将 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]]

Suppose you have a DataFrame ds and it has a column named as 'class'.假设您有一个 DataFrame ds并且它有一个名为“class”的列。 If ds ['class'] contains strings or numbers, and you want to change them with numpy.ndarray s or list s, the following code would help.如果ds ['class'] 包含字符串或数字,并且您想使用numpy.ndarraylist更改它们,则以下代码会有所帮助。 In the code, class2vector is a numpy.ndarray or list and ds_class is a filter condition.在代码中, class2vector是一个numpy.ndarraylistds_class是一个过滤条件。

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

choose eval buildin function is easy to use and easy to read.选择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)

real store display perfect human readable value:真实商店展示完美的人类可读价值:

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

Just wrap what you want to store in a cell to a list object through first apply , and extract it by index 0 of that list through second apply :只需通过第一个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

output:输出:

    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]

Here goes my 2 cents contribution (tested on Python 3.7):这是我的 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