向NumPy数组添加行/列标题

2024-09-28 01:32:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个NumPyndarray要添加行/列标题。

数据实际上是7x12x12,但我可以这样表示:

  A=[[[0, 1, 2, 3, 4, 5],
      [1, 0, 3, 4, 5, 6],
      [2, 3, 0, 5, 6, 7],
      [3, 4, 5, 0, 7, 8],
      [4, 5, 6, 7, 0, 9],
      [5, 6, 7, 8, 9, 0]]


     [[0, 1, 2, 3, 4, 5],
      [1, 0, 3, 4, 5, 6],
      [2, 3, 0, 5, 6, 7],
      [3, 4, 5, 0, 7, 8],
      [4, 5, 6, 7, 0, 9],
      [5, 6, 7, 8, 9, 0]]]

其中A是我的2x6x6阵列。

如何在第一行和第一列之间插入头,使每个数组在我的CSV输出文件中都是这样的?

        A, a, b, c, d, e, f 
        a, 0, 1, 2, 3, 4, 5,
        b, 1, 0, 3, 4, 5, 6,
        c, 2, 3, 0, 5, 6, 7,
        d, 3, 4, 5, 0, 7, 8,
        e, 4, 5, 6, 7, 0, 9,
        f, 5, 6, 7, 8, 9, 0

现在,我所做的是制作数组7x13x13并插入数据,这样我就有一行和一列零,但我更喜欢字符串。

我想我可以写一个Excel宏,用字符串替换0。但是,问题是NumPy无法将string转换为float,如果我尝试将这些零重新分配为所需的字符串。


Tags: 文件csv数据字符串numpy标题string数组
3条回答

使用^{}可以将列和索引写入文件:

import numpy as np
import pandas as pd

A = np.random.randint(0, 10, size=36).reshape(6, 6)
names = [_ for _ in 'abcdef']
df = pd.DataFrame(A, index=names, columns=names)
df.to_csv('df.csv', index=True, header=True, sep=' ')

将提供以下df.csv文件:

  a b c d e f 
a 1 5 5 0 4 4 
b 2 7 5 4 0 9 
c 6 5 6 9 7 0 
d 4 3 7 9 9 3 
e 8 1 5 1 9 0 
f 2 8 0 0 5 1    

认为这是一般的伎俩

输入

mats = array([[[0, 1, 2, 3, 4, 5],
    [1, 0, 3, 4, 5, 6],
    [2, 3, 0, 5, 6, 7],
    [3, 4, 5, 0, 7, 8],
    [4, 5, 6, 7, 0, 9],
    [5, 6, 7, 8, 9, 0]],

   [[0, 1, 2, 3, 4, 5],
    [1, 0, 3, 4, 5, 6],
    [2, 3, 0, 5, 6, 7],
    [3, 4, 5, 0, 7, 8],
    [4, 5, 6, 7, 0, 9],
    [5, 6, 7, 8, 9, 0]]])

代码

# Recursively makes pyramiding column and row headers
def make_head(n):
    pre = ''
    if n/26:
        pre = make_head(n/26-1)

    alph = "abcdefghijklmnopqrstuvwxyz"
    pre+= alph[n%26]
    return pre

# Generator object to create header items for n-rows or n-cols
def gen_header(nitems):
    n = -1
    while n<nitems:
        n+=1
        yield make_head(n)

# Convert numpy to list
lmats = mats.tolist()

# Loop through each "matrix"
for mat in lmats:
    # Pre store number of columns as we modify it before working rows
    ncols = len(mat[0])

    # add header value to front of each row from generator object
    for row,hd in zip(mat,gen_header(len(mat))):
        row.insert(0,hd)

    # Create a "header" line for all the columns
    col_hd = [hd for hd in gen_header(ncols-1)]
    col_hd.insert(0,"A")

    # Insert header line into lead row of matrix
    mat.insert(0,col_hd)

# Convert back to numpy
mats = numpy.array(lmats)

输出(存储在mats中的值):

array([[['A', 'a', 'b', 'c', 'd', 'e', 'f'],
        ['a', '0', '1', '2', '3', '4', '5'],
        ['b', '1', '0', '3', '4', '5', '6'],
        ['c', '2', '3', '0', '5', '6', '7'],
        ['d', '3', '4', '5', '0', '7', '8'],
        ['e', '4', '5', '6', '7', '0', '9'],
        ['f', '5', '6', '7', '8', '9', '0']],

       [['A', 'a', 'b', 'c', 'd', 'e', 'f'],
        ['a', '0', '1', '2', '3', '4', '5'],
        ['b', '1', '0', '3', '4', '5', '6'],
        ['c', '2', '3', '0', '5', '6', '7'],
        ['d', '3', '4', '5', '0', '7', '8'],
        ['e', '4', '5', '6', '7', '0', '9'],
        ['f', '5', '6', '7', '8', '9', '0']]], 
      dtype='|S4')

Numpy将处理n维数组,但5月份的设备仅限于二维数组。甚至不确定输出文件的外观。

许多希望命名列的人忽略了numpy的recarray()功能。好东西知道,但那只是“名字”一个维度。

对于二维空间,Pandas非常酷。

In [275]: DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])],
   .....:                      orient='index', columns=['one', 'two', 'three'])
Out[275]: 
   one  two  three
A    1    2      3
B    4    5      6

如果输出是您在这里试图解决的唯一问题,我可能会坚持使用几行手工编码的魔术,因为它比为一个功能安装另一个包要轻。

相关问题 更多 >

    热门问题