如何从numpy数组创建数据框

时间:2018-05-06 05:56:31

标签: python pandas numpy

我有以下numpy数组:

numpy_x.shape

(9982, 26)

numpy_x有9982条记录/观察值和26列索引。这是对的吗?

numpy_x[:]
array([[0.00000000e+00, 9.60000000e-01, 1.00000000e+00, ...,
        1.20000000e+00, 6.90000000e-01, 1.17000000e+00],
       [1.00000000e+00, 9.60000000e-01, 1.00000000e+00, ...,
        1.20000000e+00, 7.00000000e-01, 1.17000000e+00],
       [2.00000000e+00, 9.60000000e-01, 1.00000000e+00, ...,
        1.20000000e+00, 7.00000000e-01, 1.17000000e+00],
       ...,
       [9.97900000e+03, 6.10920994e-01, 7.58135980e-01, ...,
        1.08704204e+00, 7.88187535e-01, 1.23021669e+00],
       [9.98000000e+03, 6.10920994e-01, 7.58135980e-01, ...,
        1.08704204e+00, 7.88187535e-01, 1.23021669e+00],
       [9.98100000e+03, 6.10920994e-01, 7.58135980e-01, ...,
        1.08704204e+00, 7.88187535e-01, 1.23021669e+00]])

我想生成一个带有numpy_x数据,索引和列的数据帧(索引和列真的相同吗?),然后我继续执行以下操作:

import pandas as pd
pd.DataFrame(data=numpy_x[:], # I want pass the entire numpy array content
            index=numpy_x[1:26],
            columns=numpy_x[9982:26])

但是我收到以下错误:

/.conda/envs/x/lib/python3.6/site-packages/pandas/core/internals.py in construction_error(tot_items, block_shape, axes, e)
   4606         raise ValueError("Empty data passed with indices specified.")
   4607     raise ValueError("Shape of passed values is {0}, indices imply {1}".format(
-> 4608         passed, implied))
   4609 
   4610 

ValueError: Shape of passed values is (26, 9982), indices imply (0, 25)

如何理解indexcolumns属性传递的参数?

1 个答案:

答案 0 :(得分:1)

使用 -

numpy_x=np.random.random((100,10))
df=pd.DataFrame(numpy_x)

<强>输出

          0         1         2         3         4         5         6  \
0  0.204839  0.837503  0.696896  0.235414  0.594766  0.521302  0.841167
1  0.041490  0.679537  0.657314  0.656672  0.524983  0.936918  0.482802
2  0.318928  0.423196  0.218037  0.515017  0.107851  0.564404  0.218297
3  0.644913  0.433771  0.297033  0.011239  0.346021  0.353749  0.587631
4  0.127949  0.517230  0.969399  0.743442  0.268566  0.415327  0.567572

          7         8         9
0  0.882685  0.211414  0.659820
1  0.752496  0.047198  0.775250
2  0.521580  0.655942  0.178753
3  0.123761  0.483601  0.157191
4  0.849218  0.098588  0.754402

我想生成一个包含numpy_x数据,索引和列的数据框(索引和列真的相同吗?)

是和否。 Index只是pandas中的轴标记信息。根据轴,索引可以表示行索引或列索引。

pandas对象中的轴标记信息有多种用途:

  • 使用已知指标识别数据(即提供元数据), 对分析,可视化和交互式控制台很重要 显示
  • 启用自动和显式数据对齐
  • 允许直观获取和设置数据集的子集

它也可以是简单的单个整数索引,也可以是Multi-Index

IndexColumns参数

columns参数只是您要为数据集提供的列标签,在这种情况下,您希望为{{1}中的26列传递 26 名称数组。如果未提供列标签,则默认为numpy

np.arange(n)参数只是用于结果帧的索引。如果输入数据中没有索引信息部分且没有提供索引,则默认为index