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

查看:66
本文介绍了将行/列标题添加到 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 arrays fine, but many 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.

对于二维,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

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

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天全站免登陆