简体   繁体   中英

Select range of columns by condition in Pandas

I'd like to do something like this. Pick one or n column ranges and another column

df_premises = df.iloc[:, 0:8 and 11] equivalent to df_premises = df.iloc[:, [0,1,2,3,,8,11]]

I've tried;

  1. df_premises = df.iloc[:, 0:8, 11] - causes error
  2. df_premises = df.iloc[:, 0:8 + 11] - returns 0:18

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

Simpler solution will to define a list before that, and use the list inside iloc .

For example:

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

as mentioned in pandas documentation , input must be one of the following:

  1. An integer, eg 5.

  2. A list or array of integers, eg [4, 3, 0].

  3. A slice object with ints, eg 1:7.

  4. A boolean array.

  5. A callable function with one argument (the calling Series or DataFrame) and that returns valid output for indexing

You can use simple slicing like df.iloc[:3] or a function like df.iloc[lambda x: x.index % 2 == 0] .

So specific for what you asked about, following will work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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