将numpy.array存储在Pandas.DataFrame的单元格中 [英] Store numpy.array in cells of a Pandas.DataFrame
问题描述
我有一个要在其中存储原始" numpy.array
的数据框:
I have a dataframe in which I would like to store 'raw' numpy.array
:
df['COL_ARRAY'] = df.apply(lambda r: np.array(do_something_with_r), axis=1)
但似乎pandas
试图解包" numpy.array.
but it seems that pandas
tries to 'unpack' the numpy.array.
有解决方法吗?除了使用包装程序之外(请参见下面的修改)?
Is there a workaround? Other than using a wrapper (see edit below)?
我尝试reduce=False
失败.
编辑
这行得通,但是我必须使用'dummy'Data
类来包装数组,这不能令人满意,也不是很优雅.
This works, but I have to use the 'dummy' Data
class to wrap around the array, which is unsatisfactory and not very elegant.
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数组作为列表传递
Use a wrapper around the numpy array i.e. pass the numpy array as list
a = np.array([5, 6, 7, 8])
df = pd.DataFrame({"a": [a]})
输出:
a
0 [5, 6, 7, 8]
或者您可以通过创建元组来使用apply(np.array)
,即如果您有数据框
Or you can use apply(np.array)
by creating the tuples i.e. if you have a 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)
输出:
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')
这篇关于将numpy.array存储在Pandas.DataFrame的单元格中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!