0

I am trying to code a scenario where I need to iterate over a particular record columnwise but could not generalize it. Below is an example scenario :

input data

The output should be : if in a record, a particular column value is not null and less than 0 then code should iterate over next column value in the same index and look for any positive or null value appearing and then it should replace the negative value with that column value.

output data

so basically, in a particular record, if any cell contains negative value then code should check the next cell in the same record and should keep on checking until it finds a null or positive value and should replace the negative value with that value.

Hope the scenario is clear. I have attached input and expected output data for reference. I can write code using iterrows and if, else condition but I want to generalize the code for n number of columns. It is not possible to write 50 or 100 if else condition.

Thanks in advance for the help.

  • Please do not post link. Take some time and read [this] (https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) and consider rewrite your data and output as codes. – tianlinhe Apr 13 '20 at 19:05

1 Answers1

0

I think the easiest way is to transpose. Assume d is your dataframe:

dummy = abs(max(d.max())) + 1
d = d.fillna(dummy) #Replace none with the dummy value
d[d < 0] = None #Replace negative values with none
d = d.transpose()
d = d.fillna(method="bfill") #Backfill NA's by pulling from next row (next column in the original dataframe)
d = d.transpose() #Transpose back
d[d == dummy] = None #put dummy value back to None
mattyx17
  • 806
  • 6
  • 11
  • I cannot replace the negatives with None as there are null values already present in a dataframe which should remain as is. But it's a good addition to my knowledge. – Rahul jain Apr 13 '20 at 15:31
  • I've updated my answer. You could set the None's to some dummy value (in this case the max + 1). Then do the operations, then put the dummy value back to None – mattyx17 Apr 13 '20 at 15:56