【问题标题】:How to select multiple columns without deprecated ix in pandas如何在熊猫中选择不推荐使用 ix 的多列
【发布时间】:2019-08-28 14:08:49
【问题描述】:

在 python 中,对于 pandas 包中 DataFrame 中的数据切片,.ix 已从 pandas 0.20.0 中弃用。官方网站提供了使用 .loc.iloc 的替代解决方案来进行混合选择 (http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html)。 .index 可以帮助提取多行。相比之下,columns.get_loc 似乎最多只能选择一列。是否有可用的替代函数可用于使用 .iloc 以混合方式提取多个列?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    是的,函数被称为 Index.get_indexer 并返回列的位置或按名称列表的索引。

    这样使用:

    df = pd.DataFrame({
             'a':[4,5,4,5,5,4],
             'b':[7,8,9,4,2,3],
             'c':[1,3,5,7,1,0],
             'd':[5,3,6,9,2,4],
    }, index=list('ABCDEF'))
    print (df)
       a  b  c  d
    A  4  7  1  5
    B  5  8  3  3
    C  4  9  5  6
    D  5  4  7  9
    E  5  2  1  2
    F  4  3  0  4
    
    cols = ['a','b','c']
    df1 = df.iloc[1, df.columns.get_indexer(cols)]
    print (df1)
    a    5
    b    8
    c    3
    Name: B, dtype: int64
    
    df11 = df.iloc[[1], df.columns.get_indexer(cols)]
    print (df11)
       a  b  c
    B  5  8  3
    
    idx = ['A','C']
    df2 = df.iloc[df.index.get_indexer(idx), 2:]
    print (df2)
       c  d
    A  1  5
    C  5  6
    

    【讨论】:

      猜你喜欢
      • 2018-12-28
      • 2017-06-27
      • 2015-08-12
      • 2017-10-05
      • 2021-12-21
      • 2015-05-28
      • 1970-01-01
      • 2023-03-19
      相关资源
      最近更新 更多