python - 如何按轴选择pandas表的行索引或列索引

标签 python pandas

在pandas表中,行索引和列索引具有非常相似的接口(interface),并且某些操作允许仅通过参数axis沿行和列进行操作。 (例如 sort_index 等等。)

但是如何通过指定轴来访问(读取和写入)行索引或列索引?

# Instead of this
if axis==0:
    table.index = some_function(table.get_index_by_axis(axis))
else:
    table.column = some_function(table.get_index_by_axis(axis))

# I would like to simply write:
newIndex = some_function(table.get_index_by_axis(axis))
table.set_index_by_axis(newIndex, axis=axis)

是否存在像 get_index_by_axisset_index_by_axis 这样的东西?

更新: 数据框有一个属性 axes允许通过索引选择轴。但是,这是只读的。分配新值不会对表产生影响。

index = table.axes[axis]         # Read an index
newIndex = some_function(index)  
table.axes[axis] = newIndex      # This has no effect on table.

最佳答案

我查看了pandas源代码以了解如何使用axis关键字。有一个方法 _get_axis_name 将轴作为参数。

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

传入轴参数:

>>> df._get_axis_name(axis=0)
'index'

>>> df._get_axis_name(axis=1)
'columns'

您可以将其与 getattrsetattr 一起使用。

>>> getattr(df, df._get_axis_name(axis=0))
RangeIndex(start=0, stop=3, step=1)

>>> getattr(df, df._get_axis_name(axis=1))
Index(['A', 'B'], dtype='object')

关于python - 如何按轴选择pandas表的行索引或列索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50116623/

相关文章:

python - python-telegram-bot 的数字键盘

Python:创建新列来计算另一列中发生的次数

python - 键入具有特定列的提示 pandas 数据框

python - 在 Pandas 系列中获取唯一的名字

python - 在 Seaborn 中禁用色调嵌套

python - 使用 ManyToManyField 时出现重复字段

python - 如何在 Pygame 中为矩形添加颜色渐变?

使用带 key 的 HTTPS 连接的 Python SOAP 客户端库

python - Pandas - 分组、排序并保留第一行

Python Pandas - 从单元格中删除一个单词