3

I have a pandas DataFrame with a DateTime index and two columns called 'text' and 'labels'. I want to assign the value of labels which have value =2 and lie within a DateTime index range with value =50

I tried using,

df[df['labels']==2]['2017-02-01 05:03:25+00:00':'2017-02-01 05:05:55+00:00']['labels']=50

I am able to view the DataFrame filtered by DataTime index (rows) and columns but not able to assign it

Also tried

df.loc[df['2017-03-13 00:00:00':'2017-03-23 00:00:00'], df['labels']==2]=50

but it threw an error

df looks like

created                                text                      labels
2017-02-01 05:03:25+00:00   break john cena eyelash grow            4
2017-02-01 05:05:55+00:00   eyelash tooooo much sweeti definit      2
2017-02-01 05:14:57+00:00   come eyelash                            2

created is the DateTime index and 'text' and 'labels' are the columns of the DataFrame

df[df['labels']==2]['2017-02-01 05:03:25+00:00':'2017-02-01 05:05:55+00:00']['labels'] 

filters the DataFrame but doesn't assign it if we set it equal to a value

On assigning the DataFrame for created between '2017-02-01 05:03:25+00:00':'2017-02-01 05:05:55+00:00' and labels =2 for labels=50 I expect the result to be like this

created                                text                      labels
2017-02-01 05:03:25+00:00   break john cena eyelash grow            4
2017-02-01 05:05:55+00:00   eyelash tooooo much sweeti definit      50
2017-02-01 05:14:57+00:00   come eyelash                            2

1 Answer 1

4

Let us do get_level_values

s=df.index.get_level_values(0)
m=(s>'2017-02-01 05:03:25+00:00') & (s<='2017-02-01 05:05:55+00:00')
df.loc[m&(df.labels==2),'lable']=50
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly!! So we should give both the condition is given as row filters

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.