mapping dom
mapping dom

Reputation: 1945

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

Upvotes: 3

Views: 2401

Answers (2)

Luis l
Luis l

Reputation: 123

Exaple: When row number 300 achieves a condition, the code outputs [270:300] number of rows:

Makes windows from the condition

MINUTES_BEFORE_FOR_WINDOW_TIME = 30
rows_valid  = df_s[df_s['valid'] ==1 ].index #condition 
rows_valid_bef = [ np.r_[ i - MINUTES_BEFORE_FOR_WINDOW_TIME: i +1 ] for i  in rows_valid ]
df_s = df_s.iloc[np.concatenate(rows_valid_bef) ]#one dimension

Upvotes: 0

Roim
Roim

Reputation: 3066

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, e.g. 5.

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

  3. A slice object with ints, e.g. 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]

Upvotes: 3

Related Questions