-1

I have a column that has a range of positive and negative integers ('updated_time') and if the integer is negative I would like to add 24 to it but am having some issues. I've tried the following with no success

block_subset['updated_time'] = block_subset['updated_time'].apply(lambda x : (x + 24) if x > 
0 else x) 

Any help would be so much appreciated!

  • try: `block_subset['updated_time'] = block_subset['updated_time'].mask( block_subset['updated_time'] > 0), block_subset['updated_time'] + 24)` OR `block_subset['updated_time'] = block_subset['updated_time'].where( block_subset['updated_time'] <= 0), block_subset['updated_time'] + 24)` – David Erickson Oct 26 '20 at 23:26
  • Should your `>` be a `<` – Chris Oct 26 '20 at 23:26
  • You can also use `np.where` or `.loc` to achieve this. `mask`, `where`, `loc`, and `np.where` are all very similar for these types of operations. – David Erickson Oct 26 '20 at 23:31
  • @DavidErickson Thank you so much for the quick reply! I tried both of those and am getting the following error: Length of values does not match length of index – code_newbie Oct 26 '20 at 23:39
  • @code_newbie please include a minimum reproducible example. Please see: https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples – David Erickson Oct 26 '20 at 23:41

1 Answers1

-1

It is a lot more readable if you define a temporary variable:

t = block_subset['updated_time']
block_subset['updated_time'] = t.mask(t > 0, t + 24)

This reads "if t > 0, replace with t + 24"

Code Different
  • 90,614
  • 16
  • 144
  • 163