2013-04-29 129 views
1

说我有一维数组:充气一维数组为二维数组numpy的

import numpy as np 
my_array = np.arange(0,10) 
my_array.shape 
(10,) 

在熊猫我想创建一个数据帧只有一行,并使用这个数组10列。例如:

import pandas as pd 
import random, string 
# Random list of characters to be used as columns 
cols = [random.choice(string.ascii_uppercase) for x in range(10)] 

但是当我尝试:

pd.DataFrame(my_array, columns = cols) 

我得到:

ValueError: Shape of passed values is (1,10), indices imply (10,10) 

我想这是因为大熊猫需要一个二维数组,我有一个(平) 1D阵列。有没有办法将我的一维数组充气到二维数组中或让熊猫在创建数据框时使用一维数组?

注:我用熊猫的最新的稳定版本(0.11.0)

回答

3

你的值数组长度9,(值在1至9),并且您cols列表长度为10

我不明白你的错误信息,根据你的代码,我得到:

ValueError: Shape of passed values is (1, 9), indices imply (10, 9) 

这是有道理的。

尝试:

my_array = np.arange(10).reshape(1,10) 

cols = [random.choice(string.ascii_uppercase) for x in range(10)] 

pd.DataFrame(my_array, columns=cols) 

导致:

F H L N M X B R S N 
0 0 1 2 3 4 5 6 7 8 9 
+0

谢谢@Rutger,你是对的。我现在纠正了它。我在复制代码时犯了一个错误。 – 2013-04-29 15:23:35

1

单行,许多圆柱的数据帧是不寻常的。而更自然,地道的选择将是你所谓的cols索引的系列:

pd.Series(my_array, index=cols) 

但是,要回答你的问题,数据帧的构造是假设my_array是10个数据点的列。尝试DataFrame(my_array.reshape((1, 10)), columns=cols)。这对我行得通。

+0

'my_array.T'对1-D数组没有影响。 – 2013-04-29 15:16:52

+0

转置一维数组会得到相同的数组。您需要使用.reshape()重塑形状,或者使用np.newaxis通过reindex添加索引。 – Paul 2013-04-29 15:17:03

+0

是的,我只是测试这个,并发现这一点。我会修改.... – 2013-04-29 15:20:51

2

这两种应该这样做:

my_array2 = my_array[None] # same as myarray2 = my_array[numpy.newaxis] 

my_array2 = my_array.reshape((1,10)) 
1

通过使用替代数据帧的构造,可以无需重塑my_array创建一个数据帧中的一个。

import numpy as np 
import pandas as pd 
import random, string 
my_array = np.arange(0,10) 
cols = [random.choice(string.ascii_uppercase) for x in range(10)] 
pd.DataFrame.from_records([my_array], columns=cols) 

Out[22]: 
    H H P Q C A G N T W 
0 0 1 2 3 4 5 6 7 8 9