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

bxjv4tth  于 2023-02-06  发布在  其他
关注(0)|答案(8)|浏览(295)

我有一个 Dataframe ,我想在其中存储"原始" numpy.array

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

但是pandas似乎试图"解包" numpy.array。
是否有变通方案?除了使用 Package 器(见下面的编辑)?
我试过reduce=False,没有成功。

    • 编辑**

这是可行的,但是我必须使用'dummy' Data类来 Package 数组,这并不令人满意,也不是很优雅。

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
)
3df52oht

3df52oht1#

在numpy数组周围使用 Package 器,即以list形式传递numpy数组

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

输出:

a
0  [5, 6, 7, 8]

或者,您可以通过创建元组来使用apply(np.array)(如果您有 Dataframe

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)

输出:
一个三个三个一个
输出:

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

e0bqpujr2#

如果首先将列的类型设置为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]
7tofc5zh

7tofc5zh3#

可将数据框数据参数括在方括号中,以保持每个单元格中的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]]
cwdobuhd

cwdobuhd4#

假设您有一个DataFrame ds,并且它有一个名为“class”的列。如果 ds[“class”]包含字符串或数字,并且您希望将它们更改为numpy.ndarray s或list s,则以下代码将有所帮助。在代码中,class2vectornumpy.ndarraylistds_class 是筛选条件。
ds['class'] = ds['class'].map(lambda x: class2vector if (isinstance(x, str) and (x == ds_class)) else x)

drnojrws

drnojrws5#

chooseevalbuildin函数易于使用和阅读。

# 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']"
41ik7eoe

41ik7eoe6#

只需通过第一个apply将您想要存储在单元格中的内容 Package 到list对象中,然后通过第二个applylistindex 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]
ax6ht2ek

ax6ht2ek7#

下面是我的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]
qyswt5oh

qyswt5oh8#

如果你只想要其中的一些列,你可以这样做。以@allenyllee为例,

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

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

其输出

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

如果你需要一个特定的顺序,你也可以改变'a ',' b'的顺序。

相关问题