DataFrame - 来自嵌套字典的表中的表

2024-04-11

我使用Python 3。

这是我的数据结构:

dictionary = {
    'HexaPlex x50': {
        'Vendor': 'Dell  Inc.',
        'BIOS Version': '12.72.9',
        'Newest BIOS': '12.73.9',
        'Against M & S': 'Yes',
        'W10 Support': 'Yes',
        'Computers': {
            'someName001': '12.72.9',
            'someName002': '12.73.9',
            'someName003': '12.73.9'
        },
        'Mapped Category': ['SomeOtherCategory']
    },
    ...
}

我成功创建了一个表,显示从第一个嵌套字典的键创建的列(以'Vendor')。行名称是'HexaPlex x50'。其中一列包含带有数字的计算机,即嵌套字典:

{'someName001': '12.72.9',
 'someName002': '12.73.9',
 'someName003': '12.73.9'}

我希望能够在列下的单元格中的表格内包含键值对'Computers',实际上是一个嵌套表。

ATM机看起来像这样:

该表应该看起来有点像这样

我怎样才能实现这个目标?

此外,我想对 BIOS 版本低于最新版本的数字或单元进行着色。

我还面临这样的问题:在一种情况下,包含计算机的字典太大,即使我设置了它,它也会被缩写pd.set_option('display.max_colwidth', -1)。这看起来像这样:


正如评论中已经强调的那样,pandas 不支持“子数据帧”。为了 KISS,我建议复制这些行(或者管理两个单独的表......如果确实有必要)。

您提到的问题的答案(将 pandas 数据框单元格中的字典解析为新的行单元格(新列) https://stackoverflow.com/questions/39640936/parsing-a-dictionary-in-a-pandas-dataframe-cell-into-new-row-cells-new-columns) 导致new(框架宽)列each(行本地)“计算机名称”。考虑到您的领域模型,我怀疑这是否是您的目标。


pandas 的缩写可以通过使用其他输出引擎来规避,例如tabulate https://pypi.org/project/tabulate/ (漂亮地打印 pandas 数据框 https://stackoverflow.com/questions/18528533/pretty-printing-a-pandas-dataframe):

# standard pandas output
       Vendor BIOS Version Newest BIOS Against M & S W10 Support     Computer Location      ...          Category4     Category5     Category6     Category7     Category8     Category9     Category0
0  Dell  Inc.      12.72.9     12.73.9           Yes         Yes  someName001  12.72.9      ...       SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory
1  Dell  Inc.      12.72.9     12.73.9           Yes         Yes  someName002  12.73.9      ...       SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory
2  Dell  Inc.      12.73.9     12.73.9           Yes         Yes  someName003  12.73.9      ...       SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory

[3 rows x 17 columns]

# tabulate psql (with headers)
+----+------------+----------------+---------------+-----------------+---------------+-------------+------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+
|    | Vendor     | BIOS Version   | Newest BIOS   | Against M & S   | W10 Support   | Computer    | Location   | Category1    | Category2    | Category3    | Category4    | Category5    | Category6    | Category7    | Category8    | Category9    | Category0    |
|----+------------+----------------+---------------+-----------------+---------------+-------------+------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------|
|  0 | Dell  Inc. | 12.72.9        | 12.73.9       | Yes             | Yes           | someName001 | 12.72.9    | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory |
|  1 | Dell  Inc. | 12.72.9        | 12.73.9       | Yes             | Yes           | someName002 | 12.73.9    | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory |
|  2 | Dell  Inc. | 12.73.9        | 12.73.9       | Yes             | Yes           | someName003 | 12.73.9    | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory |
+----+------------+----------------+---------------+-----------------+---------------+-------------+------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+

# tabulate psql
+---+------------+---------+---------+-----+-----+-------------+---------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+
| 0 | Dell  Inc. | 12.72.9 | 12.73.9 | Yes | Yes | someName001 | 12.72.9 | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory |
| 1 | Dell  Inc. | 12.72.9 | 12.73.9 | Yes | Yes | someName002 | 12.73.9 | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory |
| 2 | Dell  Inc. | 12.73.9 | 12.73.9 | Yes | Yes | someName003 | 12.73.9 | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory | SomeCategory |
+---+------------+---------+---------+-----+-----+-------------+---------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+--------------+

# tabulate plain
    Vendor      BIOS Version    Newest BIOS    Against M & S    W10 Support    Computer     Location    Category1     Category2     Category3     Category4     Category5     Category6     Category7     Category8     Category9     Category0
 0  Dell  Inc.  12.72.9         12.73.9        Yes              Yes            someName001  12.72.9     SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory
 1  Dell  Inc.  12.72.9         12.73.9        Yes              Yes            someName002  12.73.9     SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory
 2  Dell  Inc.  12.73.9         12.73.9        Yes              Yes            someName003  12.73.9     SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory  SomeCategory

你也可以使用一些groupBy(..).apply(..)+ string magic 生成一个字符串表示形式,它只是隐藏重复项:

# tabulate + merge manually
+----+--------------+------------+----------------+---------------+-----------------+---------------+-------------+------------+--------------+--------------+
|    | Type         | Vendor     | BIOS Version   | Newest BIOS   | Against M & S   | W10 Support   | Computer    | Location   | Category1    | Category2    |
|----+--------------+------------+----------------+---------------+-----------------+---------------+-------------+------------+--------------+--------------|
|  0 | HexaPlex x50 | Dell  Inc. | 12.72.9        | 12.73.9       | Yes             | Yes           | someName001 | 12.72.9    | SomeCategory | SomeCategory |
|    |              |            | 12.72.9        |               |                 |               | someName002 | 12.73.9    |              |              |
|    |              |            | 12.73.9        |               |                 |               | someName003 | 12.73.9    |              |              |
+----+--------------+------------+----------------+---------------+-----------------+---------------+-------------+------------+--------------+--------------+

样式输出可以通过新的生成样式API https://pandas.pydata.org/pandas-docs/stable/style.html仍然是临时和正在开发中:

同样,您可以使用一些逻辑来“合并”列中连续的冗余值(简单的示例,我假设更多的努力可能会产生更好的输出):


Code对于上面的例子

import pandas as pd
from tabulate import tabulate
import functools

def pprint(df, headers=True, fmt='psql'):
    # https://stackoverflow.com/questions/18528533/pretty-printing-a-pandas-dataframe
    print(tabulate(df, headers='keys' if headers else '', tablefmt=fmt))

df = pd.DataFrame({
        'Type': ['HexaPlex x50'] * 3,
        'Vendor': ['Dell  Inc.'] * 3,
        'BIOS Version': ['12.72.9', '12.72.9', '12.73.9'],
        'Newest BIOS': ['12.73.9'] * 3,
        'Against M & S': ['Yes'] * 3,
        'W10 Support': ['Yes'] * 3,
        'Computer': ['someName001', 'someName002', 'someName003'],
        'Location': ['12.72.9', '12.73.9', '12.73.9'],
        'Category1': ['SomeCategory'] * 3,
        'Category2': ['SomeCategory'] * 3,
        'Category3': ['SomeCategory'] * 3,
        'Category4': ['SomeCategory'] * 3,
        'Category5': ['SomeCategory'] * 3,
        'Category6': ['SomeCategory'] * 3,
        'Category7': ['SomeCategory'] * 3,
        'Category8': ['SomeCategory'] * 3,
        'Category9': ['SomeCategory'] * 3,
        'Category0': ['SomeCategory'] * 3,
    })

print("# standard pandas print")
print(df)

print("\n# tabulate tablefmt=psql (with headers)")
pprint(df)
print("\n# tabulate tablefmt=psql")
pprint(df, headers=False)
print("\n# tabulate tablefmt=plain")
pprint(df, fmt='plain')

def merge_cells_for_print(rows, ls='\n'):
    result = pd.DataFrame()
    for col in rows.columns:
        vals = rows[col].values
        if all([val == vals[0] for val in vals]):
            result[col] = [vals[0]]
        else:
            result[col] = [ls.join(vals)]
    return result

print("\n# tabulate + merge manually")
pprint(df.groupby('Type').apply(merge_cells_for_print).reset_index(drop=True))

# https://pandas.pydata.org/pandas-docs/stable/style.html
# https://pandas.pydata.org/pandas-docs/version/0.22.0/generated/pandas.io.formats.style.Styler.apply.html#pandas.io.formats.style.Styler.apply

def highlight_lower(ref, col):
    return [f'color: {"red" if hgl else ""}' for hgl in col < ref]

def merge_duplicates(col):
    vals = col.values
    return [''] + ['color: transparent' if curr == pred else ''  for pred, curr in zip(vals[1:], vals)]

with open('only_red.html', 'w+') as f:
    style = df.style
    style = style.apply(functools.partial(highlight_lower, df['Newest BIOS']),
                        subset=['BIOS Version'])
    f.write(style.render())

with open('red_and_merged.html', 'w+') as f:
    style = df.style
    style = style.apply(functools.partial(highlight_lower, df['Newest BIOS']),
                        subset=['BIOS Version'])
    style = style.apply(merge_duplicates)
    f.write(style.render())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

DataFrame - 来自嵌套字典的表中的表 的相关文章

随机推荐

  • wpf c# 按钮等待按钮按下

    好吧 我是编码初学者 所以我想做的是按钮谁会等待用户单击多个其他按钮之一以继续 void Mainbutton the program run throw so method Wait for the user to choose one
  • 了解 htaccess 文件匹配代码

    我正在尝试将 drupal 安装在我的 bluehost 托管网站的子目录中 这是一个巨大的痛苦 我认为 htaccess 中的以下几行是问题所在 当我当前导航到 mysite com subdir install php 时 出现 403
  • SML 中的 'a 和 ''a 有什么区别?

    例如 fun example a a list list a 将有以下签名 a list gt a list 如果我定义不同但内容相同怎么办 例如 fun example a a list list a 它的签名是 a list gt a
  • Android 手持设备和穿戴设备收不到消息

    我正在尝试从可穿戴设备向手持设备发送消息 然后从手持设备向可穿戴设备发送响应 两个模块都使用相同的代码和逻辑 Gradle compile com google android support wearable 2 0 0 alpha2 c
  • 图像数据类型 SQL Server 2008 C# 数据类型

    我创建了一个数据表 CREATE TABLE ProductImages ProductImageID int IDENTITY 1 1 NOT NULL ProductImage image NOT NULL CONSTRAINT PK
  • 设置属性“system.windows.resourcedictionary.deferrablecontent”引发异常

    我正在运行 Visual Studio 2012 当我向项目添加新文件 引用时 会出现消息框并显示错误消息 设置属性 system windows resourcedictionary deferrablecontent 引发异常 我读了一
  • Linux:如何对系统内存施加负载?

    我正在开发一个小功能 它可以让我的用户了解 CPU 的占用情况 我在用着cat proc loadavg 它返回众所周知的 3 个数字 我的问题是 当我正在开发时 CPU 目前没有做任何事情 有没有一种好方法可以在CPU上产生一些负载 我在
  • iOS 不使用[电子邮件受保护]

    我有 3 张图片 test png email protected cdn cgi l email protection email protected cdn cgi l email protection 在IBOutlet中 设置一个U
  • 如何绘制高分辨率图表

    我使用 matplotlib 绘制了一些实验结果 在这里讨论过 循环文件并绘图 https stackoverflow com questions 39676294 looping over files and plotting pytho
  • 计算非凸多面体的外向法线

    如果多面体的所有节点 可能是非凸的 及其坐标已知 面的点按顺序给出 绕外法线逆时针或顺时针 如何获得每个面的外法向量脸 这是凸多面体的一种方法 计算面法线和缠绕 https stackoverflow com questions 40454
  • 使用 Angular CLI 命令安装 Bootstrap 时如何解决依赖冲突?

    我尝试使用 CLI 命令在我的 Angular 应用程序中安装 Bootstrap ng 添加 ng bootstrap ng bootstrap 但我得到了以下错误回报 使用 Angular CLI 命令安装 Bootstrap 时如何解
  • NHibernate 中的延迟加载

    如果客户有很多订单 如何使用 NHibernate 延迟加载订单列表 是不是需要设置映射文件 任何帮助或例子都会很棒 克里斯的建议是我如何做到这一点 但是如果您想在运行时执行此操作 您可以根据您的标准将 Fetchmode 设置为惰性 如下
  • 忽略忽略属性

    我们有 MSTest 测试 它会在每小时的生产中自动运行 其中一项测试标有 Ignore 属性 因为它还没有准备好在我们的生产环境中运行它 现在我想 仅 在我的本地环境上启动该测试 因为我的本地环境已准备好进行该测试 我尝试通过单击测试代码
  • 将 select 的背景颜色设置为 JQuery 中选定的选项

    这个问题的后续 在 JQuery 中设置选择选项的背景颜色 https stackoverflow com questions 5065167 setting background color of select options in jq
  • FluentMigrator 失败的迁移不回滚?

    我刚刚开始尝试流利迁移器 http github com enkari fluentmigrator readme 我注意到失败的迁移不会被回滚 这还没有实施吗 这看起来相当糟糕 因为它使数据库处于损坏状态 例如 当第二次尝试添加 Tabl
  • 当窗口未最大化时缺少 WM_NCLBUTTONUP 消息的奇怪问题

    我有一个处理 WM NCLBUTTONUP 消息的窗口 以便处理标题栏中自定义按钮的点击 当窗口最大化时 这非常有效 但当窗口未最大化时 WM NCLBUTTONUP 消息永远不会到达 不过我确实收到了 WM NCLBUTTONDOWN 消
  • 对于连接到单个服务器的多个客户端,我应该使用哪种双向 ZeroMQ 模式?

    我有多个 数千个 客户端连接到单个服务器并发送一些日志数据 服务器分析数据并在必要时做出响应 PUB SUB是一个方向 监视器示例 REQ REP无法识别对等方并专门回复对等方 仅适用于 ACK 等 我需要注册这些客户端 识别他们并能够在分
  • Rails中防止重复记录的正确方法

    在我的模型中我有这个 validates name presence gt true uniqueness gt true 在我的控制器中我有 if location save format html redirect to locatio
  • Docker 通过命令或文件设置环境变量

    我需要设置一个环境变量CLASSPATH 在该变量中 我需要设置命令的结果 hadoop classpath glob 这将返回大量的 java 库 并且它们都需要设置到其中CLASSPATH多变的 最大的问题是我只能在 docker 构建
  • DataFrame - 来自嵌套字典的表中的表

    我使用Python 3 这是我的数据结构 dictionary HexaPlex x50 Vendor Dell Inc BIOS Version 12 72 9 Newest BIOS 12 73 9 Against M S Yes W1