numpy不同数据类型的多维数组

时间:2017-11-23 10:27:52

标签: python pandas numpy

我想将2d数据插入numpy并作为pandas中的数据框投影。 基本上它有10行5列。所有5列的数据类型都是订单 (int,string,int,string,string)。

_MaxRows = 10

_MaxColumns = 5


person = np.zeros([_MaxRows,5])


person

def personGen():
    for i in range(0,_MaxRows): 
            # add person dynamically
        # person[i][0] = i
        # person[i][1] = names[i]
        # person[i][2] = random.randint(10,50)
        # person[i][3] = random.choice(['M','F'])
        # person[i][4] = 'Desc'


personGen()

输出需要作为数据框

Id Name Age Gender Desc
1  Sumeet 12 'M' 'HELLO'
2  Sumeet2 13 'M' 'HELLO2'

2 个答案:

答案 0 :(得分:1)

在同一个numpy数组中不能有不同的数据类型。您可以使用一个线性numpy数组列表,每个数组都有自己的数据类型。

e.g。像这样:

names = ["asd", "shd", "wdf"]
ages = np.array([12, 35, 23])

d = {'name': names, 'age': ages}
df = pd.DataFrame(data=d)

答案 1 :(得分:1)

根据yar的答案进行构建:

同一numpy(单多维)维数组中不能有不同的数据类型。 您可以在numpy的结构化数组中使用不同的数据类型。

_MaxRows = 2
_MaxNameSize = 7
_MaxDescSize = 4

names = ['Sumeet', 'Sumeet2']

data = list(
    [(i, names[i], random.randint(10,50), random.choice(['M', 'F']), 'Desc') for i in range(0,_MaxRows)]
)

nparray = numpy.array(data, dtype=[('id', int), ('name', f'S{_MaxNameSize}'), ('age', int), ('Gender', 'S1'), ('Desc', f'S{_MaxDescSize}')])

# if you cannot specify string types size you can do like below, however I've read it decreases numpys operations performance because it removes the benefit of the array's data contiguous memory usage.
# nparray = numpy.array(data, dtype=[('id', int), ('name', object), ('age', int), ('Gender', 'S1'), ('Desc', object)])

print('Numpy structured array:\n', nparray)

pddataframe = pd.DataFrame(nparray)

print('\nPandas dataframe:\n', pddataframe)

默认情况下,Panda的数据框已经为您的传入数据创建了一个索引(0、1,..)。因此,您可以选择不通知“ id”列。