0

If I have a pandas dataframe that looks like this:

     X [ m ]  Y [ m ]  Z [ m ]
0         1     1      0.0
1         2     0.5    0.1
2         3     2      0.3
3         4     1      0.4
4         5     3      0.5 
5         1     4      0.6
6         2     1.5    0.8
7         3     6      1.0
8         4     3      1.2
9         5     4      1.5
...

How would I add a fourth column (Z_2) that would look like this (only include values that are a 0.5 jump):

     X [ m ]  Y [ m ]  Z [ m ]  Z_2 [ m ]
0         1     1      0.0      0.0
1         2     0.5    0.1      0.0
2         3     2      0.3      0.5
3         4     1      0.4      0.5
4         5     3      0.5      0.5
5         1     4      0.6      0.5
6         2     1.5    0.8      1.0 
7         3     6      1.0      1.0
8         4     3      1.2      1.0
9         5     4      1.5      1.5 
...
1
  • Is Z always increasing? Can it contain negative numbers? If so do you want -1.3 to go to -1.0 (round towards zero) or -1.5 (round down)? Commented Aug 20, 2020 at 15:37

2 Answers 2

2

You can try :

df["Z_2"] = (df["Z"] // 0.5) * 0.5

If you're talking about only 0.5 "jump"in the Z column.

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

Comments

0

You could try something like:

df["Z_2"] = (df["Z"] % .5 == 0).cumsum() * .5

Here the df["Z"] % .5 == 0 finds the values in df["Z"] that are on the .5 boundary, the cumsum will only add 1 when a True is encountered.

2 Comments

This will only work if Z is monotonically increasing and it never skips a multiple of 0.5 right? If Z had [... 0.4, 0.6...] then wouldn't 0.6 still get rounded to 0 in this case? Granted the OP is quite ambiguous on this point.
Yep that’s a valid point. I suppose I had assumed the values are sorted. If they’re unsorted your solution seems like the best one

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.