Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在数据帧列中存储多维数组_Python_Pandas - Fatal编程技术网

Python 在数据帧列中存储多维数组

Python 在数据帧列中存储多维数组,python,pandas,Python,Pandas,我希望使用熊猫作为主轨迹(MCMC参数空间中的一系列点)对象 我有一个字符串->数组的dict列表,我想存储在pandas中。DICT中的键始终相同,对于每个键,numpy数组的形状始终相同,但对于不同的键,形状可能不同,并且可能具有不同的维数 我一直在使用self.append(dict\u list,ignore\u index=True),它似乎适用于1d值,但对于nd>1值,pandas将值存储为对象,这不允许进行漂亮的打印和其他漂亮的事情。关于如何获得更好的行为有什么建议吗 样本数据

我希望使用熊猫作为主轨迹(MCMC参数空间中的一系列点)对象

我有一个字符串->数组的dict列表,我想存储在pandas中。DICT中的键始终相同,对于每个键,numpy数组的形状始终相同,但对于不同的键,形状可能不同,并且可能具有不同的维数

我一直在使用
self.append(dict\u list,ignore\u index=True)
,它似乎适用于1d值,但对于nd>1值,pandas将值存储为对象,这不允许进行漂亮的打印和其他漂亮的事情。关于如何获得更好的行为有什么建议吗

样本数据

point = {'x': array(-0.47652306228698005),
         'y': array([[-0.41809043],
                     [ 0.48407823]])}

points = 10 * [ point]
我希望能做一些类似的事情

df = DataFrame(points)

而且

>> df['x'][1].shape
()
>> df['y'][1].shape 
(2,1)

这有点违背熊猫的哲学,熊猫似乎将
系列
视为一维数据结构。因此,您必须手动创建
系列
,告诉他们数据类型为
“object”
。这意味着不要应用任何自动数据转换

您可以这样做(重新排序的Ipython会话):


相对较新的库X射线[1]有
数据集
数据阵列
结构,它们完全可以满足您的要求

以下是我对您问题的看法,以IPython会话的形式编写:

In [9]: import pandas as pd

In [1]: point = {'x': array(-0.47652306228698005),
   ...:          'y': array([[-0.41809043],
   ...:                      [ 0.48407823]])}

In [2]: points = 10 * [ point]

In [5]: lx = [p["x"] for p in points]

In [7]: ly = [p["y"] for p in points]

In [40]: sx = pd.Series(lx, dtype=numpy.dtype("object"))

In [38]: sy = pd.Series(ly, dtype=numpy.dtype("object"))

In [43]: df = pd.DataFrame({"x":sx, "y":sy})

In [45]: df['x'][1].shape
Out[45]: ()

In [46]: df['y'][1].shape
Out[46]: (2, 1)
以下是迄今为止我们构建的两个
DataArray
实例:

>>> print(da_x)
<xray.DataArray (x: 10)>
array([-0.47652306, -0.47652306, -0.47652306, -0.47652306, -0.47652306,
       -0.47652306, -0.47652306, -0.47652306, -0.47652306, -0.47652306])
Coordinates:
  * x        (x) int32 0 1 2 3 4 5 6 7 8 9


>>> print(da_y.T) ## Transposed, to save lines.
<xray.DataArray (y1: 1, y0: 2, x: 10)>
array([[[-0.41809043, -0.41809043, -0.41809043, -0.41809043, -0.41809043,
         -0.41809043, -0.41809043, -0.41809043, -0.41809043, -0.41809043],
        [ 0.48407823,  0.48407823,  0.48407823,  0.48407823,  0.48407823,
          0.48407823,  0.48407823,  0.48407823,  0.48407823,  0.48407823]]])
Coordinates:
  * x        (x) int32 0 1 2 3 4 5 6 7 8 9
  * y0       (y0) int32 0 1
  * y1       (y1) int32 0
我们最终可以按照您想要的方式访问和聚合数据:

>>> ds['X'].sum()
<xray.DataArray 'X' ()>
array(-4.765230622869801)


>>> ds['Y'].sum()
<xray.DataArray 'Y' ()>
array(0.659878)


>>> ds['Y'].sum(axis=1)
<xray.DataArray 'Y' (x: 10, y1: 1)>
array([[ 0.0659878],
       [ 0.0659878],
       [ 0.0659878],
       [ 0.0659878],
       [ 0.0659878],
       [ 0.0659878],
       [ 0.0659878],
       [ 0.0659878],
       [ 0.0659878],
       [ 0.0659878]])
Coordinates:
  * x        (x) int32 0 1 2 3 4 5 6 7 8 9
  * y1       (y1) int32 0

>>> np.all(ds['Y'].sum(axis=1) == ds['Y'].sum(dim='y0'))
True

>>>> ds['X'].sum(dim='y0')
Traceback (most recent call last):
ValueError: 'y0' not found in array dimensions ('x',)
>ds['X'].sum()
阵列(-4.765230622869801)
>>>ds['Y'].sum()
阵列(0.659878)
>>>ds['Y'].和(轴=1)
数组([[0.0659878],
[ 0.0659878],
[ 0.0659878],
[ 0.0659878],
[ 0.0659878],
[ 0.0659878],
[ 0.0659878],
[ 0.0659878],
[ 0.0659878],
[ 0.0659878]])
协调:
*x(x)int32 01 2 3 4 5 6 7 8 9
*y1(y1)int32 0
>>>np.all(ds['Y'].sum(轴=1)=ds['Y'].sum(dim='y0'))
真的
>>>>ds['X'].sum(dim='y0')
回溯(最近一次呼叫最后一次):
ValueError:在数组维度('x',)中找不到“y0”
[1] 一个用于处理带有标签的N维数据的库,就像pandas处理2D:

一样,将@Eike和@JohnSalvatier的评论结合在一起似乎非常泛达索式:

要绘制(并执行所有其他酷炫的二维操作),您仍然需要手动将数组列转换回数据帧:

>>> dfy = pd.DataFrame([row.T[0] for row in df2.y])
>>> dfy += np.matrix([[0] * 10, range(10)]).T
>>> dfy *= np.matrix([range(10), range(10)]).T
>>> dfy.plot()

要将其存储在磁盘上,请使用
进行pickle

>>> df.to_pickle('/tmp/sotest.pickle')
>>> df2 = pd.read_pickle('/tmp/sotest.pickle')
>>> df.y[0].shape
# (2, 1)
如果您使用
来_csv
您的
np.array
将变成字符串:

>>> df.to_csv('/tmp/sotest.csv')
>>> df2 = pd.DataFrame.from_csv('/tmp/sotest.csv')
>>> df2.y[0]
# '[[-0.41809043]\n [ 0.48407823]]'

你们研究过数据结构吗?但不确定它是否有助于您的用例……我们可以为您的问题提供示例数据吗?当然,我已经在上面添加了一些。这有用吗?或者您想要更多的东西吗?请尝试
多索引
熊猫。现在不推荐使用pandas面板
,建议使用或(以前的X射线)最好知道这是取消pandas。我认为df.append(points)方法基本上可以做到这一点。
>>> import pandas as pd
>>> np = pandas.np
>>> point = {'x': np.array(-0.47652306228698005),
...          'y': np.array([[-0.41809043],
...                         [ 0.48407823]])}
>>> points = 10 * [point]  # this creates a list of 10 point dicts
>>> df = pd.DataFrame().append(points)
>>> df.x
# 0    -0.476523062287
#   ...
# 9    -0.476523062287
# Name: x, dtype: object
>>> df.y
# 0    [[-0.41809043], [0.48407823]]
#   ...
# 9    [[-0.41809043], [0.48407823]]
# Name: y, dtype: object
>>> df.y[0]
# array([[-0.41809043],
#        [ 0.48407823]])
>>> df.y[0].shape
# (2, 1)
>>> dfy = pd.DataFrame([row.T[0] for row in df2.y])
>>> dfy += np.matrix([[0] * 10, range(10)]).T
>>> dfy *= np.matrix([range(10), range(10)]).T
>>> dfy.plot()
>>> df.to_pickle('/tmp/sotest.pickle')
>>> df2 = pd.read_pickle('/tmp/sotest.pickle')
>>> df.y[0].shape
# (2, 1)
>>> df.to_csv('/tmp/sotest.csv')
>>> df2 = pd.DataFrame.from_csv('/tmp/sotest.csv')
>>> df2.y[0]
# '[[-0.41809043]\n [ 0.48407823]]'