在熊猫数据框中读取np数组

时间:2020-03-31 18:44:19

标签: python pandas numpy

我有一组看起来像这样的数据:

12 , 12 , 12 , 12    #Data 1
16 , 16 , 16 , 16    #Data 2
3  , 3  , 3  , 3     #Data 3
3  , 3  , 3  , 3     ..
2  , 2  , 2  , 2     ..
9  , 9  , 9  , 9     ..
15 , 15 , 15 , 15    ..

和数据按行排列,如图所示。

现在,我需要在pandas中使用这些数据。问题是,根据我的有限知识,panda按列而不是按行读取数据。

因此,(出于某种其他原因),我读取了numpy中的数据,并尝试将numpy数组读取为熊猫:

#!/usr/bin/env python3

import numpy as np
import pandas

names = ["A", "B", "C", "D", "E", "F", "G"]
data = np.genfromtxt("trial.dat", delimiter=',')
print(type(data))
print(data)
dataset = pandas.DataFrame(data=data, columns=names)

正在给出:

python3 mwe.py 
<class 'numpy.ndarray'>
[[12. 12. 12. 12.]
 [16. 16. 16. 16.]
 [ 3.  3.  3.  3.]
 [ 3.  3.  3.  3.]
 [ 2.  2.  2.  2.]
 [ 9.  9.  9.  9.]
 [15. 15. 15. 15.]]
ValueError: Wrong number of items passed 4, placement implies 7
ValueError: Shape of passed values is (7, 4), indices imply (7, 7)

不匹配基本上是由名称维度引起的,

names = ["A", "B", "C", "D"]

和 打印(数据集)

我得到:

class 'numpy.ndarray'>
[[12. 12. 12. 12.]
 [16. 16. 16. 16.]
 [ 3.  3.  3.  3.]
 [ 3.  3.  3.  3.]
 [ 2.  2.  2.  2.]
 [ 9.  9.  9.  9.]
 [15. 15. 15. 15.]]
      A     B     C     D
0  12.0  12.0  12.0  12.0
1  16.0  16.0  16.0  16.0
2   3.0   3.0   3.0   3.0
3   3.0   3.0   3.0   3.0
4   2.0   2.0   2.0   2.0
5   9.0   9.0   9.0   9.0
6  15.0  15.0  15.0  15.0

但是在Pandas数据集中,我想要:

A    B 
12   16
12   16
12   16
12   16 

等,即沿着and-array的行。

那么,我怎样才能将np-ndarray读到熊猫?

1 个答案:

答案 0 :(得分:1)

转置np_array

dataset = pandas.DataFrame(data=data.T, columns=names)