在熊猫中按条件选择列范围

时间:2020-06-05 15:05:50

标签: python python-3.x pandas

我想做这样的事情。选择一个或n个列范围,然后选择另一列

df_premises = df.iloc[:, 0:8 and 11]等同于df_premises = df.iloc[:, [0,1,2,3,,8,11]]

我已经尝试过了

  1. df_premises = df.iloc[:, 0:8, 11]-导致错误
  2. df_premises = df.iloc[:, 0:8 + 11]-返回0:18

1 个答案:

答案 0 :(得分:3)

您可以使用:df.iloc[:, lambda x: x.index < 9 or x.index == 11]

更简单的解决方案是在此之前定义一个列表,然后在iloc中使用该列表。

例如:

my_range = range(9)
my_range.append(11)
df_premises = df.iloc[:, my_range]

pandas documentation中所述,输入必须是以下之一:

  1. 一个整数,例如5。

  2. 一个整数列表或数组,例如[4,3,0]。

  3. 具有整数的切片对象,例如1:7。

  4. 一个布尔数组。

  5. 具有一个参数(调用Series或DataFrame)的可调用函数,该函数返回有效的输出以进行索引

您可以使用像df.iloc[:3]这样的简单切片,或者像df.iloc[lambda x: x.index % 2 == 0]这样的函数。

针对您所要求的内容,以下方法将起作用:

df.iloc[:, lambda x: x.index < 9 or x.index == 11]