繁体   English   中英

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

[英]DataFrame - table in table from nested dictionary

我使用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) ,包含计算机的词典也是如此以至于它被缩写。 看起来像这样:

字典字符串的特写

正如评论中已经强调的那样,熊猫不支持“子数据帧”。 为了KISS的缘故,我建议复制这些行(或在必要时管理两个单独的表...)。

您提到的问题的答案( 将pandas数据单元格中的字典解析为新的行单元格(新列) )将为每个 (行本地)“计算机名”产生新的 (全帧)列。 考虑到域模型,我怀疑这是您的目标。


可以使用其他输出引擎来规避pandas的缩写,例如, 制表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(..) +字符串魔术来产生仅表示重复项的字符串表示形式:

# 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    |              |              |
+----+--------------+------------+----------------+---------------+-----------------+---------------+-------------+------------+--------------+--------------+

样式输出可以通过新的Styling API生成,该API仍是临时的并且正在开发中

样式的熊猫输出,其中一些单元格以红色突出显示

再次,您可以使用一些逻辑来“合并”列中的连续冗余值(快速示例,我认为付出更多的努力可能会导致更好的输出):

样式的熊猫输出,其中一些单元格以红色突出显示,而某些则隐藏


以上示例的代码

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())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM