3

With a DataFrame like the one below, how do I set c1len equal to zero when c1pos equals zero? I would then like to do the same for c2len/c2pos. Is there an easy way to do it without creating a bunch of columns to arrive at the desired answer?

             distance  c1pos  c1len  c2pos  c2len  daysago
 line_date                                                
 2013-06-22      7.00      9    0.0      9    6.4       27
 2013-05-18      8.50      6    4.6      7    4.9       62
 2012-12-31      8.32      5    4.6      5    2.1      200
 2012-12-01      8.00      7    7.1      6    8.6      230
 2012-11-03      7.00      7    0.0      7    2.7      258
 2012-10-15      7.00      7    0.0      8    5.2      277
 2012-09-22      8.32     10   10.1      8    4.1      300
 2012-09-15      9.00     10   12.5      9   12.1      307
 2012-08-18      7.00      8    0.0      8    9.2      335
 2012-08-02      9.00      5    3.5      5    2.2      351
 2012-07-14     12.00      3    4.5      3    3.5      370
 2012-06-16      8.32      7    3.7      7    5.1      398

1 Answer 1

6

I do't think you have anything that actually satifies those conditions, but this will work

This creates a boolean mask for when the rows of the column in question (e.g. c2pos) are 0; then it is setting the column c2len to 0 for those that are True

In [15]: df.loc[df.c2pos==0,'c2len'] = 0

In [16]: df.loc[df.c1pos==0,'c1len'] = 0

In [17]: df
Out[17]: 
            distance  c1pos  c1len  c2pos  c2len  daysago
2013-06-22      7.00      9    0.0      9    6.4       27
2013-05-18      8.50      6    4.6      7    4.9       62
2012-12-31      8.32      5    4.6      5    2.1      200
2012-12-01      8.00      7    7.1      6    8.6      230
2012-11-03      7.00      7    0.0      7    2.7      258
2012-10-15      7.00      7    0.0      8    5.2      277
2012-09-22      8.32     10   10.1      8    4.1      300
2012-09-15      9.00     10   12.5      9   12.1      307
2012-08-18      7.00      8    0.0      8    9.2      335
2012-08-02      9.00      5    3.5      5    2.2      351
2012-07-14     12.00      3    4.5      3    3.5      370
2012-06-16      8.32      7    3.7      7    5.1      398
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect. I didn't realize the sample given didn't have any qualifying rows. The actual frame is hundreds of rows... thank you!!
gr8, extensive documentation here

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.