如何使Pandas DataFrame(Python)以二维(2D)矩阵格式显示每个单元格 [英] how to make Pandas DataFrame (Python) to display each cell in a two dimensional (2-D) matrix format

查看:36
本文介绍了如何使Pandas DataFrame(Python)以二维(2D)矩阵格式显示每个单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用在Python中导入的MatLab结构创建二维(2-D)数据结构。

当我使用Pandas.DataFrame时,每个单元格都包含一个矩阵,但是它们以列表格式显示。我正在尝试将其更改为矩阵格式。

使用以下代码时,Python中的DataFrame将类似于: (然而,它并不相同,因为实际数据是从MatLab导入的,并且具有不同的类型,而我不能使用python重新创建它)

import pandas as pd
k=[[0,1,2,3,4,5,6]]
df=pd.DataFrame(k)
df[:] = df[:].astype('object')
df.at[0,0] = [[1]]
df.at[0,1] = [[1.0,2.0],[2.0,4.0],[8.0,3.0],[9.0,7.0]]
df.at[0,2] = [[0.487],[1.532],[1.544],[1.846]]
df.at[0,3] = [[3.0]]
df.at[0,4] = [[3.0]]
df.at[0,5] = [[-1]]
df.at[0,6] = [[]]
display(df)

哪些结果

(您也可以通过运行以下代码片段找到类似的结果。)

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>0</th>
      <th>1</th>
      <th>2</th>
      <th>3</th>
      <th>4</th>
      <th>5</th>
      <th>6</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>[[1]]</td>
      <td>[[1.0, 2.0], [2.0, 4.0], [8.0, 3.0], [9.0, 7.0]]</td>
      <td>[[0.487], [1.5326], [1.544], [1.846]]</td>
      <td>[[3.0]]</td>
      <td>[[3.0]]</td>
      <td>[[-1]]</td>
      <td>[[]]</td>
    </tr>
  </tbody>
</table>

如您所见,每个单元格显示为列表,即:

(您也可以通过运行以下代码片段找到类似的结果。)

<body>
    [[1.0, 2.0], [2.0, 4.0], [8.0, 3.0], [9.0, 7.0]]
</body>

我正在尝试将其更改为类似

的内容

(您也可以通过运行以下代码片段找到类似的结果。)

数据-lang="js"数据-隐藏="真"数据-控制台="真"数据-巴贝尔="假">
.matrix {
        position: relative;
    }
    .matrix:before, .matrix:after {
        content: "";
        position: absolute;
        top: 0;
        border: 1px solid #000;
        width: 6px;
        height: 100%;
    }
    .matrix:before {
        left: -10px;
        border-right: -0;
    }
    .matrix:after {
        right: -10px;
        border-left: 0;
    }
<div align=center>
  <table class="matrix">
    <tr>
      <td>1</td>
      <td>2</td>
    </tr>
    <tr>
      <td>2</td>
      <td>4</td>
    </tr>
    <tr>
      <td>8</td>
      <td>3</td>
    </tr>
    <tr>
      <td>9</td>
      <td>7</td>
    </tr>
  </table>
</div>

谢谢。

推荐答案

@Attack68,这是我在回复您漂亮的答案时提到的代码。 请记住,正如我所提到的,实际数据是从MatLab结构中导入的。这意味着它不能处理我在问题本身中提供的数据,但可以很好地处理使用scipy.io导入到python中的MatLab结构。 我在link@Valdi_Bo答案和<3-1]>的@Paul Panzer答案的帮助下编写了此代码。

df = pd.DataFrame(data)

import re 
def pretty_col(data):
     data=np.array(data)
     if data.size <= 1:
         return format(data)
     else:
         return format(data[:, None])[1:-1].replace('[', 'u23A1', 1).replace(' [', 'u23A2', data.size-2).replace(' [', 'u23A3').replace(']', 'u23A4', 1).replace(']', 'u23A5', data.size-2).replace(']', 'u23A6')
def pretty_cols(data, comma=False):
    if comma:
        f='
'.join(line[0] + line + line[-1] for line in map(str.join, data.shape[0] // 2 * ('  ',) + (', ',) + (data.shape[0] - 1) // 2 * ('  ',), zip(*map(str.split, map(pretty_col, data.T), data.shape[1]*('
',)))))
    else:
        f='
'.join(line[0] + line + line[-1] for line in map(''.join, zip(*map(str.split, map(pretty_col, data.T), data.shape[1]*('
',)))))
    return f

def myFmt(txt):
    if txt=="":
        return "[]"
    else:
        q=r'<font">bananas
</font>'
        q=q.replace("bananas", repr(txt))
        q=q.replace("'", '')
        return q.replace(r'
', '<br>')
def ttest(x):
    for i,k in enumerate(x):
        for j,l in enumerate(k):
            x[i][j]=float(format(l, '.2f'))
            return x

def transform(tdf,prec):
    for col in tdf.columns:
        tdf[col] = tdf[col].apply(pretty_cols)
        for j in range(len(tdf[col])):
            tdf[col][j]=fixing_newline(tdf[col][j],prec)


print(df[df.columns[0]])
def fixing_newline(string,prec):
    string=string.replace("⎡⎡", ' aa ').replace("⎤⎤", ' bb ').replace("
", ' cc ').replace("⎢⎢", ' dd ').replace("⎥⎥", ' ee ').replace("⎣⎣", ' ff ').replace("⎦⎦", ' gg ').replace("[[", ' hh ').replace("]]", ' kk ')
    chunks = string.split(' ')
    string=""
    for i,k in enumerate(chunks):
        try: 
            string+=str("{:."+str(prec)+"f}").format(float(k))
        except ValueError:
            string+=k
    string=string.replace("aa", "⎡⎡").replace("bb", '⎤⎤').replace("cc", '
').replace("dd", '⎢⎢').replace("ee", '⎥⎥').replace("ff", '⎣⎣').replace("gg", '⎦⎦').replace("hh", '[[').replace("kk", ']]')
    return string


transform(df,3)
df=df.style.format(myFmt)

display(df)

这将导致类似如下的结果: Results(需要有关内联图像的帮助,因为我没有足够的声誉。)

但是,代码根本没有效率,而且也不能一直很好地工作。

这篇关于如何使Pandas DataFrame(Python)以二维(2D)矩阵格式显示每个单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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