Python nontype operation

Asked 2 years ago, Updated 2 years ago, 34 views

TypeError: unsupported operand type(s) for -: 'NoneType' and 'NoneType'

If the nontype is included when Python specifies the operation, I want to return it as a NULL value How do I write code?

For example, I want to reflect the difference between the two values as NULL when there is list A and list B, and when there is nontype among elements of A and nontype among elements of B.

python mysql

2022-09-22 17:55

2 Answers

>>> a = [ 3, 4, 5, None , 7, 8 ]
>>> b = [ 1, 2, None, 10, 9, 8 ]
>>> diff = [ x-y if None not in (x, y) else None for x, y in zip(a, b) ]
>>> diff
[2, 2, None, None, -2, 0]


>>> import pandas as pd
>>> df = pd.DataFrame({'a':a, 'b':b})
>>> df
     a     b
0  3.0   1.0
1  4.0   2.0
2  5.0   NaN
3  NaN  10.0
4  7.0   9.0
5  8.0   8.0
>>> df['diff'] = df.a - df.b
>>> df
     a     b  diff
0  3.0   1.0   2.0
1  4.0   2.0   2.0
2  5.0   NaN   NaN
3  NaN  10.0   NaN
4  7.0   9.0  -2.0
5  8.0   8.0   0.0
>>> 


2022-09-22 17:55

None in python is NULL.

There can't be a price difference.

If it's NoneType, you can't do arithmetic in the first place.

Is the purpose of calculating the values of each of the two lists with the same index?

If there is a None value during the arithmetic process, can it not be processed?


2022-09-22 17:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.