Python 将 numpy.array 存储在 Pandas.DataFrame 的单元格中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45548426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Store numpy.array in cells of a Pandas.DataFrame
提问by Cedric H.
I have a dataframe in which I would like to store 'raw' numpy.array
:
我有一个数据框,我想在其中存储 'raw' 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.
这有效,但我必须使用 'dummy'Data
类来环绕数组,这令人不满意且不是很优雅。
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
)
回答by Bharath
Use a wrapper around the numpy array i.e. 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 i.e. 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')
回答by user1717828
You can wrap the Data Frame data args in square brackets to maintain the np.array
in each cell:
您可以将 Data Frame 数据 args 包裹在方括号中以维护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]]
回答by yuzhen_3301
Suppose you have a DataFrame ds
and it has a column named as '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. In the code, class2vector
is a numpy.ndarray
or list
and ds_class
is a filter condition.
假设您有一个 DataFrameds
并且它有一个名为“class”的列。如果ds
['class'] 包含字符串或数字,并且您想用numpy.ndarray
s 或list
s更改它们,则以下代码会有所帮助。在代码中,class2vector
是一个numpy.ndarray
或,list
并且ds_class
是一个过滤条件。
ds['class'] = ds['class'].map(lambda x: class2vector if (isinstance(x, str) and (x == ds_class)) else x)
ds['class'] = ds['class'].map(lambda x: class2vector if (isinstance(x, str) and (x == ds_class)) else x)
回答by allenyllee
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
:
只是包装你想在一个单元格中存放了什么list
,通过第一个对象apply
,并提取它index 0
的是list
通过第二apply
:
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]
回答by David Wasserman
If you first set a column to have type object
, you can insert an array without any wrapping:
如果您首先将一列设置为具有 type 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]