繁体   English   中英

Select 按条件在 Pandas 中的列范围

[英]Select range of columns by condition in 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

您可以使用: 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 文档中所述,输入必须是以下之一:

  1. 一个 integer,例如 5。

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

  3. 带有整数的切片 object,例如 1:7。

  4. boolean 阵列。

  5. 带有一个参数(调用系列或数据帧)的可调用 function 并返回有效的 output 用于索引

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

因此,针对您所询问的内容,以下内容将起作用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM