Python 如何按轴选择表的行索引或列索引
在pandas表中,行索引和列索引有一个非常相似的界面,一些操作允许通过参数Python 如何按轴选择表的行索引或列索引,python,pandas,Python,Pandas,在pandas表中,行索引和列索引有一个非常相似的界面,一些操作允许通过参数axis沿行和列进行操作。(例如,还有更多。) 但如何通过指定轴来访问(读写)行索引或列索引 # 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)) #
axis
沿行和列进行操作。(例如,还有更多。)
但如何通过指定轴来访问(读写)行索引或列索引
# 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\u index\u by\u axis
和set\u index\u by\u axis
的内容
更新:
数据帧具有允许按索引选择轴的属性。但是,这是只读的。指定新值不会对表产生影响
index = table.axes[axis] # Read an index
newIndex = some_function(index)
table.axes[axis] = newIndex # This has no effect on table.
我查看了pandas源代码以了解axis关键字是如何使用的。有一个方法
\u get\u axis\u 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')
使用:
好主意。但它依赖于未被记录的大熊猫特征。考虑到“列”和“索引”有如此多的相似之处,我想知道为什么没有为它们建立抽象。是的,这将是一个很好的添加功能。我遇到你的问题是因为我正要问同样的问题。
import pandas as pd
def apply_axis(df, axis, func):
old_index = df.axes[axis]
new_index = old_index.map(func)
df = df.set_axis(new_index, axis=axis)
return df
def some_function(x):
return x+x
df = pd.DataFrame({'a': [1,2,3],
'b': [10,20,30],
'c': [100,200,300],
'd': [1000,2000,3000]})
# a b c d
# 0 1 10 100 1000
# 1 2 20 200 2000
# 2 3 30 300 3000
ret = apply_axis(df=df, axis=0, func=some_function)
# a b c d
# 0 1 10 100 1000
# 2 2 20 200 2000
# 4 3 30 300 3000
ret = apply_axis(df=df, axis=1, func=some_function)
# aa bb cc dd
# 0 1 10 100 1000
# 1 2 20 200 2000
# 2 3 30 300 3000