3

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
1

2 Answers 2

3

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]

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks is this the same as stackoverflow.com/questions/41256648/… ?
Same but different ways. Both works, use what is simpler for your opinion. For you case I like the more direct use of lambda
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.