将numpy ndarray数据放入熊猫

时间:2014-05-02 16:22:13

标签: python arrays numpy multidimensional-array pandas

我想将以下数据放入pandas进行进一步分析。

import numpy as np
import pandas as pd
from pandas import DataFrame

data = np.array([[[1, 1, 1, np.nan, 1], [np.nan, 1, 1, 1, 1]],
                 [[2, np.nan, 2, 2, 2], [2, np.nan, 2, 2, 2]],
                 [[3, 3, 3, np.nan, 3], [3, 3, 3, 3, np.nan]]])

pnda = pd.Series(data)

print pnda

但发生以下错误:

Exception: Data must be 1-dimensional

这样做的好方法是什么?我的进一步分析是通过用三次或多项式方法插值来填充np.nan值,并将结果输出为numpy数组。

2 个答案:

答案 0 :(得分:3)

尝试使用面板:

import numpy as np
import pandas as pd

data = np.array([[[1, 1, 1, np.nan, 1], [np.nan, 1, 1, 1, 1]],
                 [[2, np.nan, 2, 2, 2], [2, np.nan, 2, 2, 2]],
                 [[3, 3, 3, np.nan, 3], [3, 3, 3, 3, np.nan]]])

x = pd.Panel(data)
x

<class 'pandas.core.panel.Panel'>
Dimensions: 3 (items) x 2 (major_axis) x 5 (minor_axis)
Items axis: 0 to 2
Major_axis axis: 0 to 1
Minor_axis axis: 0 to 4

和...

print(x.loc[0])
    0  1  2   3  4
0   1  1  1 NaN  1
1 NaN  1  1   1  1

答案 1 :(得分:2)

根据您的评论,您可以在重塑data时实现所需,使用DataFrame.interpolate()方法进行插值,然后将数组恢复为原始值。它适用于 pandas 0.13.1

df = pd.DataFrame(data.reshape(2, -1))
df.interpolate(axis=1).values.reshape(data.shape)
#array([[[1, 1, 1, 1, 1],
#        [1, 1, 1, 1, 1]],
#
#       [[2, 2, 2, 2, 2],
#        [2, 2, 2, 2, 2]],
#
#       [[3, 3, 3, 3, 3],
#        [3, 3, 3, 3, 3]]], dtype=int64)