子集参数在 pandas.io.formats.style.Styler.format 中起什么作用?

2024-02-13

的公共文档pandas.io.formats.style.Styler.format https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.formats.style.Styler.format.html says

subset : 索引切片
一个论据DataFrame.loc限制哪些元素formatter被应用于.

But 看代码 https://github.com/pandas-dev/pandas/blob/cc3daa6f7e140e870d57c3b02a5d2142e11d09c9/pandas/io/formats/style.py#L478,这不太正确...这是什么_non_reducing_slice stuff?

    if subset is None:
        row_locs = range(len(self.data))
        col_locs = range(len(self.data.columns))
    else:
        subset = _non_reducing_slice(subset)
        if len(subset) == 1:
            subset = subset, self.data.columns

        sub_df = self.data.loc[subset]

用例:我想格式化特定的行,但是当我天真地遵循文档并使用可以正常工作的内容时,我收到错误.loc[]:

>>> import pandas as pd
>>>
>>> df = pd.DataFrame([dict(a=1,b=2,c=3),dict(a=3,b=5,c=4)])
>>> df = df.set_index('a')
>>> print df
   b  c
a
1  2  3
3  5  4
>>> def J(x):
...     return '!!!%s!!!' % x
...
>>> df.style.format(J, subset=[3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\io\formats\style.py", line 372, in format
    sub_df = self.data.loc[subset]
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\indexing.py", line 1325, in __getitem__
    return self._getitem_tuple(key)
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\indexing.py", line 841, in _getitem_tuple
    self._has_valid_tuple(tup)
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\indexing.py", line 189, in _has_valid_tuple
    if not self._has_valid_type(k, i):
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\indexing.py", line 1418, in _has_valid_type
    (key, self.obj._get_axis_name(axis)))
KeyError: 'None of [[3]] are in the [columns]'
>>> df.loc[3]
b    5
c    4
Name: 3, dtype: int64
>>> df.loc[[3]]
   b  c
a
3  5  4

好的,我尝试使用IndexSlice它看起来很不稳定——在某些情况下有效,在其他情况下不起作用,至少在 Pandas 0.20.3 中:

Python 2.7.14 |Anaconda custom (64-bit)| (default, Oct 15 2017, 03:34:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas as pd
>>> import numpy as np
>>> idx = pd.IndexSlice
>>> r = np.arange(16).astype(int)
>>> colors = 'red green blue yellow'.split()
>>> df = pd.DataFrame(dict(a=[colors[i] for i in r//4], b=r%4, c=r*100)).set_index(['a','b'])
>>> print df
             c
a      b
red    0     0
       1   100
       2   200
       3   300
green  0   400
       1   500
       2   600
       3   700
blue   0   800
       1   900
       2  1000
       3  1100
yellow 0  1200
       1  1300
       2  1400
       3  1500
>>> df.loc[idx['yellow']]
      c
b
0  1200
1  1300
2  1400
3  1500
>>> def J(x):
...     return '!!!%s!!!' % x
...
>>> df.style.format(J,idx['yellow'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\io\formats\style.py", line 372, in format
    sub_df = self.data.loc[subset]
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\indexing.py", line 1325, in __getitem__
    return self._getitem_tuple(key)
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\indexing.py", line 836, in _getitem_tuple
    return self._getitem_lowerdim(tup)
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\indexing.py", line 948, in _getitem_lowerdim
    return self._getitem_nested_tuple(tup)
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\indexing.py", line 1023, in _getitem_nested_tuple
    obj = getattr(obj, self.name)._getitem_axis(key, axis=axis)
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\indexing.py", line 1541, in _getitem_axis
    return self._getitem_iterable(key, axis=axis)
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\indexing.py", line 1081, in _getitem_iterable
    self._has_valid_type(key, axis)
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\indexing.py", line 1418, in _has_valid_type
    (key, self.obj._get_axis_name(axis)))
KeyError: "None of [['yellow']] are in the [columns]"
>>> pd.__version__
u'0.20.3'

在 pandas 0.24.2 中,我收到类似的错误,但略有不同:

>>> df.style.format(J,idx['yellow'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\io\formats\style.py", line 401, in format
    sub_df = self.data.loc[subset]
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\indexing.py", line 1494, in __getitem__
    return self._getitem_tuple(key)
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\indexing.py", line 868, in _getitem_tuple
    return self._getitem_lowerdim(tup)
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\indexing.py", line 969, in _getitem_lowerdim
    return self._getitem_nested_tuple(tup)
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\indexing.py", line 1048, in _getitem_nested_tuple
    obj = getattr(obj, self.name)._getitem_axis(key, axis=axis)
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\indexing.py", line 1902, in _getitem_axis
    return self._getitem_iterable(key, axis=axis)
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\indexing.py", line 1205, in _getitem_iterable
    raise_missing=False)
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\indexing.py", line 1161, in _get_listlike_indexer
    raise_missing=raise_missing)
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\indexing.py", line 1246, in _validate_read_indexer
    key=key, axis=self.obj._get_axis_name(axis)))
KeyError: u"None of [Index([u'yellow'], dtype='object')] are in the [columns]"
>>> pd.__version__
u'0.24.2'

哦等等——我没有指定足够的索引信息;这有效:

df.style.format(J,idx['yellow',:])

我同意你表现出的行为并不理想。

>>> df = (pandas.DataFrame([dict(a=1,b=2,c=3),
                            dict(a=3,b=5,c=4)])
            .set_index('a'))
>>> df.loc[[3]]
   b  c
a      
3  5  4
>>> df.style.format('{:.2f}', subset=[3])
Traceback (most recent call last)
...
KeyError: "None of [Int64Index([3], dtype='int64')] are in the [columns]"

您可以通过传递完整的形式来解决此问题pandas.IndexSlice作为子集参数:

>>> df.style.format('{:.2f}', subset=pandas.IndexSlice[[3], :])

既然你问什么_non_reducing_slice()正在做,它的目标是合理的(确保子集不会将维度降维为系列)。它的实现将列表视为一系列列名:

From 熊猫/核心/indexing.py https://github.com/pandas-dev/pandas/blob/c0f6428b097f6e1a1765d8d07cb695169f442e66/pandas/core/indexing.py#L2477-L2506:

def _non_reducing_slice(slice_):
    """
    Ensurse that a slice doesn't reduce to a Series or Scalar.

    Any user-paseed `subset` should have this called on it
    to make sure we're always working with DataFrames.
    """
    # default to column slice, like DataFrame
    # ['A', 'B'] -> IndexSlices[:, ['A', 'B']]
    kinds = (ABCSeries, np.ndarray, Index, list, str)
    if isinstance(slice_, kinds):
        slice_ = IndexSlice[:, slice_] 
    ...

我想知道文档是否可以改进:在这种情况下,引发的异常subset=[3]匹配的行为df[[3]]而不是df.loc[[3]].

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

子集参数在 pandas.io.formats.style.Styler.format 中起什么作用? 的相关文章

随机推荐

  • 如何告诉 Valgrind 完全抑制特定的 .so 文件?

    我正在尝试在我正在开发的程序上使用 Valgrind 但 Valgrind 为我正在使用的库之一生成一堆错误 我希望能够告诉它抑制涉及该库的所有错误 我可以为抑制文件提出的最接近的规则是 rule name Memcheck Cond ob
  • javascript: 这个关键字

    I know this指向函数操作的当前对象 所以这是根据定义的代码 function foo alert this output window 所以 现在函数 foo 等于 window foo 但现在在这里 function foo f
  • 为什么这个 Haskell 程序中没有使用尾部调用优化?

    以下程序会破坏堆栈 find first occurrence Eq b gt b gt b gt Int gt Int find first occurrence e i 1 find first occurrence e x xs i
  • *tmp*[[j]] 中的错误:下标超出范围

    抱歉帖子太长 我是 R 新手 一直在努力提高对这门语言的掌握 我偶然发现了这个有趣的足球结果建模项目 http www1 maths leeds ac uk voss projects 2010 sports JamesGardner pd
  • 如何检查某种情况是否持续超过 15 分钟?

    以下是数据集的示例 Date Value 2020 01 01 01 35 50 2020 01 01 01 41 49 2020 01 01 01 46 50 我想检查连续 15 分钟的 值 是否等于 50 如果是 我想提取它发生的日期
  • 触摸事件 (touchesMoved) 不适用于 UIScrollView 内的 UIView

    我有一个UIView里面一个UIScrollView 以及UIViewControllers对于那些没有接收触摸事件的视图 如果我将视图从滚动视图中取出 那么它就可以工作 UserInteraction 在所有视图中都是默认打开的 但它仍然
  • 如何授予特定用户对特定节点的编辑权限?

    如何授予特定用户对特定节点的编辑权限 我有一个名为 学生 的用户角色 多个用户具有该角色 但只有少数用户可以编辑节点 我怎样才能意识到这一点 我将尝试介绍一些用例 以及如何解决它们 If all members of a category
  • 插入行并获取生成的 ID

    我正在尝试使用 Spring 的JdbcTemplate类将行插入到名为的 MySQL 表中transaction并获取生成的ID 相关代码是 public Transaction insertTransaction final Trans
  • 如何使用 Objective C 更改 iOS 设备的系统壁纸/背景?

    我很好奇是否可以通过您自己的应用程序以编程方式更改 iOS 设备的系统壁纸 背景 Apple 不提供公共 API 来执行此操作 用户必须通过 设置 应用程序选择要用作壁纸的图片 您可以让您的应用将图片保存到用户保存的照片中 并指示用户手动更
  • 如何在 Symfony 2.0 中使用元标签

    我不知道如何在我网站的所有页面中添加元标签 正确的 您可以将元标记放入网站的基本布局中 对于更复杂的愿望 您可以将它们放入一个块中 如果您愿意 您可以在特定模板中覆盖它们 有关更多信息 请查看 Symfony2 文档创建和使用模板 http
  • Javascript 正则表达式模式 \W 是否包含空格?

    我正在使用这个表达 W g匹配除数字 字母和空格之外的所有字符 好像是包含空格的 我将如何构建一个不包含空格的正则表达式 a z0 9 s ig 解释 Character class which matches characters NOT
  • 找到沿两个平面相交的线

    我试图在 3D 中绘制由两个平面相交形成的线 但我无法理解数学 这已被解释过here http mathinsight org intersecting planes examples and here http mathworld wol
  • 如何使用 Espresso 点击 Android 图库

    我们目前正在使用 Espresso 测试一个 Android 应用程序 我们要测试的功能之一是从本地图片库中选择图片 图像 我们可以一路调出图库视图 但无法在结果窗口中从 最近 下载 图库 中进行选择 下面包含了我们如何取得如此进展的一个片
  • Watir Webdriver 计算 UL 列表中的项目数量

    我进行了一些搜索 但无法找到合适的答案 基本上我有一个长度不同的无序列表 我想遍历列表 做一些其他事情 然后返回并选择列表中的下一个项目 当我定义循环应该迭代的次数时 我可以很好地做到这一点 因为我知道列表中的项目数量 但是我不想为每个测试
  • python 3,尝试从多个 HID 输入读取,Raspberry Pi

    我有一个条形码扫描仪连接到我的 RasPi 没有任何 tty 这意味着没有显示器的无头 换句话说 数字输入的键盘记录器 该扫描仪可读取 GTIN 或 EAN 等数字条形码 它有效 脚本在启动时由 sh 启动 我使用的脚本如下所示 impor
  • 合并多个 BatchEncoding 或从 BatchEncoding 对象列表创建张量流数据集

    在标记标记任务中 我使用转换器标记生成器 它输出 BatchEncoding 类的对象 我分别对每个文本进行标记 因为我需要从文本中提取标签并在标记后重新排列它们 由于子标记 但是 我找不到一种方法可以从 BatchEncoding 对象列
  • 如何通知其他应用程序我的应用程序是 Windows 桌面的一部分?

    我想在 C 中为 Windows 创建一个 工具栏 并希望将其放置在 Windows 桌面的顶部空间 我希望其他 Windows 程序无法覆盖我的应用程序 我还希望其他应用程序将我的窗口视为桌面的一部分 以便当它们最大化时 您仍然可以看到我
  • Matlab调试:跳过下一行而不执行

    问题 问题的完整描述如下 有人对如何欺骗 Matlab 跳过一行或多行代码有建议吗 mex java 重写一些内部Matlab功能 有谁知道在哪里db 代码文件可能位于 如果存在 Matlab 中有几个函数可以在调试 运行程序时进行流量控制
  • 将所有提交导出到 ZIP 文件或目录中

    如何将所有提交导出到 ZIP 文件 包含全部文件 不仅仅是补丁 差异 myproject commit1 67d91ab zip myproject commit2 9283acd zip myproject commit3 c57daa6
  • 子集参数在 pandas.io.formats.style.Styler.format 中起什么作用?

    的公共文档pandas io formats style Styler format https pandas pydata org pandas docs stable reference api pandas io formats st