Sarbadal Pal
Sarbadal Pal

Reputation: 21

Adding Calculated Field in DataFrame

I would like to create a column called str_bos in a existing DataFrame called result. I have the following columns - 'str_nbr', 'ZIP Sales', 'str_Sales', 'ZIP_Distinct #', 'ZIP_Share_of_Str_Sales', 'Counter', 'Str_BOS_Cum%', 'Str_Sales_Rank'.

Here is what I've come up with. But, it takes 2 hours to complete. However, other operations (like sort, merge etc.) take a few seconds. What I'm missing here?

def str_bos(row):
    if row['str_sales_rank'] == 1 or row['str_bos_cum%'] <= 0.1:
        return 1
    elif row['str_bos_cum%'] <= 0.2:
        return 2
    elif row['str_bos_cum%'] <= 0.3:
        return 3
    elif row['str_bos_cum%'] <= 0.4:
        return 4
    elif row['str_bos_cum%'] <= 0.5:
        return 5
    elif row['str_bos_cum%'] <= 0.6:
        return 6
    elif row['str_bos_cum%'] <= 0.7:
        return 7
    elif row['str_bos_cum%'] <= 0.8:
        return 8
    elif row['str_bos_cum%'] <= 0.9:
        return 9
    else:
        return 10

result['str_bos'] = result.apply(lambda row: str_bos(row), axis=1)

Upvotes: 1

Views: 293

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210832

I'd use cut() method here:

In [21]: df = pd.DataFrame(np.random.rand(10), columns=['A'])

In [22]: df
Out[22]:
          A
0  0.513425
1  0.973631
2  0.549615
3  0.747600
4  0.099415
5  0.737613
6  0.885567
7  0.720187
8  0.446683
9  0.434688

In [23]: df['str_bos'] = pd.cut(df.A, bins=np.arange(0, 1.1, 0.1), labels=np.arange(10)+1)

In [24]: df
Out[24]:
          A str_bos
0  0.513425       6
1  0.973631      10
2  0.549615       6
3  0.747600       8
4  0.099415       1
5  0.737613       8
6  0.885567       9
7  0.720187       8
8  0.446683       5
9  0.434688       5

Upvotes: 1

Related Questions