How to get a value on a 3rd column in dataframe depending on the difference between the first and second columns?

Viewed 715

So, I have a table as follows:

start end 5 5 4 8 10 19 4 4

Now what I want to do is, if the value on the two columns in a particular row is equal, then print only one of them in the 3rd column. If they are different, then print - start + "-" + end. The data is in a dataframe. Example is this:

start end range 5 5 5 4 8 4-8 10 19 10-19 4 4 4

This is the code I am trying:

if df['start'] - df['end'] != 0:
   df['range'] = df['start'] + "-" + df['end']
else:
   df['range'] = df['start']

But this is not working. How can I do this?

1 Answers

Use numpy.where:

df['range'] = np.where(df['start'] != df['end'], df['start'] + "-" + df['end'], df['start'])

Similar another solution:

df['range'] = df['start'] + np.where(df['start'] != df['end'], "-" + df['end'], '')

print (df)
  start end  range
0     5   5      5
1     4   8    4-8
2    10  19  10-19
3     4   4      4

Solution if values are not strings:

s = df['start'].astype(str) 
e = df['end'].astype(str)

df['range'] = np.where(df['start'] != df['end'], s + "-" + e, s)

Similar another solution:

df['range'] = s + np.where(df['start'] != df['end'], "-" + e, '')
Related