在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_axis
和 set_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'
您可以将其与 getattr
或 setattr
一起使用。
>>> 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/