0

I have two columns floors and floor total

df = pd.DataFrame({"floor": [1,2,30], "floors_total": [1, 50, 30]})

I want to write a function such as if in a row both values in floors total and floor are equal then return "last floor" and then if floor = 1 then return "first floor" and if other return "other" I want to apply this to df

I am trying to write a for loop which is :

def new(df):
  a = "floor"
  b = "floors_total"
  for a,b in df.iteritems():
    if a == b:
      return "last floor"
    elif a == 1:
      return "first floor"
    else:
      return "other"
df["floor_postiton"] = df.apply(new)

I am getting all rows in the new column as NaN

Neekunj
  • 35
  • 6

1 Answers1

1

You can avoid the (slow) iteration over the dataframe with np.where:

df['floor_position'] = np.where(df['floor'] == df['floors_total'],
                'last floor',
                np.where(df['floor'] == 1, 'first floor',
                     'other'))
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252