向NumPy数组添加行/列标题 [英] Adding row/column headers to NumPy arrays

查看:989
本文介绍了向NumPy数组添加行/列标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NumPy ndarray,我想向其中添加行/列标题.

I have a NumPy ndarray to which I would like to add row/column headers.

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

The data is actually 7x12x12, but I can represent it like this:

  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数组.

where A is my 2x6x6 array.

如何在第一行和第一列中插入标题,以便每个数组在我的CSV输出文件中看起来像这样?

How do I insert headers across the first row and the first column, so that each array looks like this in my CSV output file?

        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并插入数据,使得行和列的零值都为零,但我更喜欢字符串.

Right now, what I have done is made the array 7x13x13 and inserted the data such that I have a row and column of zeros, but I'd much prefer strings.

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

I guess I could just write an Excel macro to replace the zeros with strings. However, the problem is that NumPy cannot convert string to float, if I try to reassign those zeros as the strings I want.

推荐答案

Numpy可以处理n维数组的罚款,但可能的功能仅限于2维数组.甚至不确定您希望输出文件的外观.

Numpy will handle n-dimensional array's fine but may of the facilities are limited to 2 dimensional arrays. Not even sure how you want the output file to look.

许多希望使用命名列的人忽略了 recarray( ) numpy的功能.要知道的好东西,但只能命名"一个维度.

Many people who would wish for named columns overlook the recarray() capabilities of numpy. Good stuff to know but that only "names" one dimension.

对于两个维度,熊猫非常酷.

For two dimensions, Pandas is very cool.

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

如果输出是您要在此处解决的唯一问题,那么我可能只会坚持使用几行手工编码的魔术,因为它比为一个功能安装另一个软件包要轻得多.

If output is the only problem you are trying to solve here, I'd probably just stick with a few lines of hand coded magic as it will be less weighty than installing another package for one feature.

这篇关于向NumPy数组添加行/列标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆