1

I have a dataframe df that looks like:

           A       B
0          0    4140
1   0.142857    1071
2          0    1196
3   0.090909    2110
4   0.083333    1926
5   0.166667    1388
6          0    3081
7          0    1149
8          0    1600
9   0.058824    1873
10         0    3960
:          :       :
19         0    4315
20         0    2007
21  0.086957    3323
22  0.166667    1084
23       0.5    2703
24         0    1214
25         0    1955
26         0    6750
27         0    3240
28         0    1437
29         0    1701

I am trying to use the following line of code is trying to produce a new column which divides A/B if A is greater than 0 (else populate with 0) and then mutiply by 90:

df['new_column'] = np.where(df['A'] = 0, 0.0, df['A'].divide(df['B']))*90.0

However I get the error for the line:

 result[:] = [tuple(x) for x in values]

TypeError: 'int' object is not iterable

The desired output for new_column is:

           A     B   new_column
0          0  4140            0
1   0.142857  1071   0.01200479
2          0  1196            0
3   0.090909  2110  0.003877635
4   0.083333  1926  0.003894065
5   0.166667  1388  0.010806938
6          0  3081            0
7          0  1149            0
8          0  1600            0
9   0.058824  1873  0.002826567
10         0  3960            0
 :         :     :            :
19         0  4315            0
20         0  2007            0
21  0.086957  3323   0.00235514
22  0.166667  1084  0.013837666
23       0.5  2703  0.016648169
24         0  1214            0
25         0  1955            0
26         0  6750            0
27         0  3240            0
28         0  1437            0
29         0  1701            0

1 Answer 1

2

Note that numpy.where works as:

numpy.where(condition[, x, y])

Therefore:

import pandas as pd

df = pd.DataFrame({'A':[0,0.142857,0,0.090909],
                   'B':[4140,1071,1196,2110]})

df['new_column'] = np.where(df['A'] > 0, df['A']*90/df['B'], 0)

output

           A       B    new_column
0   0.000000    4140    0.000000
1   0.142857    1071    0.012005
2   0.000000    1196    0.000000
3   0.090909    2110    0.003878
Sign up to request clarification or add additional context in comments.

1 Comment

@d_kennetz because if A is less than or equal to 0, the value has to be 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.