1

I have a small dataframe below of spending of 4 persons. There is an empty column called 'Grade'. I would like to rate those who spent more than $100 grade A, and grade B for those less than $100. What is the most efficient method of filling up column 'Grade', assuming it is a big dataframe?

import pandas as pd
df=pd.DataFrame({'Customer':['Bob','Ken','Steve','Joe'],
             'Spending':[130,22,313,46]})
df['Grade']=''

enter image description here

unclegood
  • 277
  • 5
  • 14
  • Possible duplicate of [Python Pandas: Add column based on other column](http://stackoverflow.com/questions/35424567/python-pandas-add-column-based-on-other-column) – Wondercricket Dec 15 '16 at 13:57

2 Answers2

1

Fastest way to do that would be to use lambda function with an apply function.

df['grade'] = df.apply(lambda row: 'A' if row['Spending'] > 100 else 'B', axis = 1)
Vikash Singh
  • 13,213
  • 8
  • 40
  • 70
1

You can use numpy.where:

df['Grade']= np.where(df['Spending'] > 100 ,'A','B')
print (df)
  Customer  Spending Grade
0      Bob       130     A
1      Ken        22     B
2    Steve       313     A
3      Joe        46     B

Timings:

df=pd.DataFrame({'Customer':['Bob','Ken','Steve','Joe'],
             'Spending':[130,22,313,46]})

#[400000 rows x 4 columns]
df = pd.concat([df]*100000).reset_index(drop=True)

In [129]: %timeit df['Grade']= np.where(df['Spending'] > 100 ,'A','B')
10 loops, best of 3: 21.6 ms per loop

In [130]: %timeit df['grade'] = df.apply(lambda row: 'A' if row['Spending'] > 100 else 'B', axis = 1)
1 loop, best of 3: 7.08 s per loop
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252