将1D数组膨胀为numpy的2D数组 [英] Inflating a 1D array into a 2D array in numpy
问题描述
说我有一个一维数组:
import numpy as np
my_array = np.arange(0,10)
my_array.shape
(10, )
在Pandas中,我想使用此数组创建一个只有一行和10
列的DataFrame.例子:
In Pandas I would like to create a DataFrame with only one row and 10
columns using this array. FOr example:
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)
我认为这是因为Pandas需要2D数组,而我有一个(平坦的)1D数组.有没有办法将我的1D数组充气到2D数组中,或者让Panda在创建数据框时使用1D数组?
I presume this is because Pandas expects a 2D array, and I have a (flat) 1D array. Is there a way to inflate my 1D array into a 2D array or have Panda use a 1D array in the creation of the dataframe?
注意:我使用的是熊猫的最新稳定版本(0.11.0)
Note: I am using the latest stable version of Pandas (0.11.0)
推荐答案
您的值数组的长度为9(值从1到9),并且您的cols
列表的长度为10.
Your value array has length 9, (values from 1 till 9), and your cols
list has length 10.
根据您的代码,我不理解您的错误消息,我得到:
I dont understand your error message, based on your code, i get:
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
这篇关于将1D数组膨胀为numpy的2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!