【问题标题】:iloc for cutting data for a spare set of columns by indexiloc 用于按索引切割一组备用列的数据
【发布时间】:2022-01-17 22:55:08
【问题描述】:
df = pd.DataFrame({'name':['jack', 'james', 'joe'], 'age':[30, 40, 50], 'height': [6.0, 5.9, 5.5], 'is_married':[1,0,1], 'is_parent':[0,1,1]})

我只想选择列索引:0、2、3、4(但不是 1)。以下工作正常:

df_cut = df.iloc[:,[0,2,3,4]]

但不是传递每个特定的列索引,而是寻找一种可以传递的方法。我试过了:

df_cut = df.iloc[:,[0,[2:4]]

但它不起作用。最好的解决方案是什么?

【问题讨论】:

    标签: python pandas data-analysis


    【解决方案1】:

    你需要来自numpynp.r_

    df_cut = df.iloc[:,np.r_[0,2:4+1]]
    df_cut
    Out[338]: 
        name  height  is_married  is_parent
    0   jack     6.0           1          0
    1  james     5.9           0          1
    2    joe     5.5           1          1
    

    【讨论】:

      【解决方案2】:

      删除索引 1 处的列:

      df_cut = df.drop(df.columns[1], axis=1)
      

      或者使用range:

      df_cut = df.iloc[:,[0]+list(range(2,5))]
      

      【讨论】:

        【解决方案3】:

        另一种方式:

        df_cut = df[ [col for col_index, col in enumerate(df) if col_index != 1]]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-19
          相关资源
          最近更新 更多