fred.schwartz
fred.schwartz

Reputation: 2155

Pandas index if statement

I'm trying to make a new column of 1's if the index is greater than x in a pandas dataframe.

But this code isn't working. Anyone have any ideas?

if df.index>=3:
    df['Step1']=1
else:
    df['Step1']=0

Upvotes: 0

Views: 1573

Answers (1)

rawwar
rawwar

Reputation: 5012

lets take an example dataframe as below

df  = pd.DataFrame({"a":[1,2,3,4,5],"b":[2,4,9,16,25]})

index method prints as below

In [4]: df.index
Out[4]: RangeIndex(start=0, stop=5, step=1)

and df.index >3 prints as below

In [5]: df.index>3
Out[5]: array([False, False, False, False,  True])

so, answer is

y = df.index>3
df['new_column'] = y.astype(int)
df
   a   b  new_column
0  1   2    0
1  2   4    0
2  3   9    0
3  4  16    0
4  5  25    1

Edit: if you want to do between 3 and 9 indexes you do the following

import numpy as np
np.logical_and(df.index>2, df.index<5)
array([False, False, False,  True,  True])

Upvotes: 3

Related Questions