I have an issue and I have no idea what is causing it.. I have a very very simply dataframe which looks like the following;
JavaScript
x
10
10
1
A B
2
01/01/2022 -34 -102.34
3
02/01/2022 -4 -89.23
4
03/01/2022 -78 -43.2
5
.
6
.
7
.
8
31/12/2022 -32 -34.21
9
10
I simply need to convert this dataframe to positive numbers. When I do this with a simple;
JavaScript
1
3
1
df = df * -1
2
3
A column multiples but the B column loses its’ data to the following;
JavaScript
1
10
10
1
A B
2
01/01/2022 34
3
02/01/2022 4
4
03/01/2022 78
5
.
6
.
7
.
8
31/12/2022 32
9
10
I assume this is something to do with interger vs float64 but just can’t crack it.
Any help much appreciated!
Advertisement
Answer
You likely have strings in your data, multiplying a string by an integer less than 1 converts to empty string:
JavaScript
1
3
1
df = pd.DataFrame({'A': [0,1,2], 'B': [0,'1',2]})
2
df*-1
3
output:
JavaScript
1
5
1
A B
2
0 0 0
3
1 -1
4
2 -2 -2
5
Workaround: convert to_numeric
:
JavaScript
1
5
1
df.apply(pd.to_numeric, errors='coerce')*-1
2
3
# or
4
# df.astype(float)*-1
5
output:
JavaScript
1
5
1
A B
2
0 0 0
3
1 -1 -1
4
2 -2 -2
5