Starting from a df like that:
Lev. | Qta | Text | Qty |
---|---|---|---|
.1 | 1 | Model3 | 1 |
.2 | 2 | Gruoup1 | 1 |
.3 | 5 | Gruoup1.1 | 4 |
.3 | 1 | Gruoup1.2 | 1 |
.3 | 2 | Gruoup1.3 | 1 |
.3 | 1 | Gruoup1.4 | |
.3 | 1 | Gruoup1.5 |
I want to create a new column comparing two different columns, for do this I defined a function like this:
def F1(k):
if (k['Lev'] == '.1'):
return 'Expl1'
elif (k['Lev'] == '.2'):
return 'Expl2'
elif (k['Qtà'] == k['Qty']):
return 'OK'
elif (k['Qtà'] > k['Qty']):
return 'NOK'
elif (k['Qtà'] < k['Qty']):
return 'Less'
elif (k['Qty'] is empty):
return'NoMap'
else
Return 'Check'
df['OK/NOK'] = df.apply(F1, axis=1)
The function works well except when in QTY I have an empty cell. When the cell is empty i receive 'Check' answer.
This is an example of what would like to obtain:
Lev. | Qta | Text | Qty | OK/NOK. |
---|---|---|---|---|
.1 | 1 | Model3 | 1 | Expl1 |
.2 | 2 | Gruoup1 | 1 | Expl2. |
.3 | 5 | Gruoup1.1 | 4 | Less. |
.3 | 1 | Gruoup1.2 | 1 | OK. |
.3 | 2 | Gruoup1.3 | 1 | NOK. |
.3 | 1 | Gruoup1.4 | NoMap. | |
.3 | 1 | Gruoup1.5 | NoMap. |
CodePudding user response:
I think it's the "is empty" test, without more context it's hard to tell:
def F1(k):
if k['Lev'] == '.1':
return 'Expl1'
elif k['Lev'] == '.2':
return 'Expl2'
elif k['Qtà'] == k['Qty']:
return 'OK'
elif k['Qtà'] > k['Qty']:
return 'NOK'
elif k['Qtà'] < k['Qty']:
return 'Less'
elif not k['Qty']:
return 'NoMap'
else
Return 'Check'
df['OK/NOK'] = df.apply(F1, axis=1)
CodePudding user response:
You could use a vectorial approach.
A possibility is to use numpy.select
with all individual conditions.
import numpy as np
df['OK/NOK'] = np.select([df['Lev'] == '.1', df['Lev'] == '.2', ...],
['Expl1', 'Expl2', ...],
'Check')
Another one would be to use a pandas approach:
import numpy as np
r1 = df['Lev'].map({'.1': 'Expl1', '.2': 'Expl2'})
r2 = np.sign(df['Qta']-df['Qty']).map({1: 'NOK', 0: 'OK', -1: 'LESS'})
r3 = pd.isna(df['Qty']).map({True: 'NoMap', False: 'Check'})
df['OK/NOK'] = r1.fillna(r2).fillna(r3)
output:
Lev Qta Text Qty OK/NOK
0 .1 1 Model3 1.0 Expl1
1 .2 2 Gruoup1 1.0 Expl2
2 .3 5 Gruoup1.1 4.0 NOK
3 .3 1 Gruoup1.2 1.0 OK
4 .3 2 Gruoup1.3 1.0 NOK
5 .3 1 Gruoup1.4 NaN NoMap
6 .3 1 Gruoup1.5 NaN NoMap