【问题标题】:How to choose row-index or column-index of pandas table by axis如何按轴选择熊猫表的行索引或列索引
【发布时间】:2021-03-15 21:49:24
【问题描述】:

在 pandas 表中,row-index 和 column-index 具有非常相似的接口,并且一些操作允许通过参数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.

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我查看了 pandas 源代码以了解如何使用轴关键字。有一个方法_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')
    

    【讨论】:

    • 好主意。但它依赖于 pandas 的一个未记录的特性。我想知道为什么没有为“列”和“索引”建立抽象,因为它们有很多相似之处。
    • 是的,添加它会是一个很好的功能。我遇到了你的问题,因为我正要问同样的事情。
    【解决方案2】:

    使用pd.DataFrame.set_axis():

    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
    
    

    【讨论】:

      猜你喜欢
      • 2020-07-17
      • 2018-05-28
      • 2020-01-01
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      • 2016-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多