i am having one DataFrame as shown below,i want to convert the decimal number to integer without rounding.
JavaScript
x
8
1
Date A B
2
01-01-2022 12.87 0.67
3
02-01-2022 3.8976 123.98
4
03-01-2022 6.7654 23.98
5
04-01-2022 2.897 0.098
6
05-01-2022 3.986 0.76
7
06-01-2022 1.09 12.45
8
Desired output:
JavaScript
1
8
1
Date A B
2
01-01-2022 12 0
3
02-01-2022 3 123
4
03-01-2022 6 23
5
04-01-2022 2 0
6
05-01-2022 3 0
7
06-01-2022 1 12
8
Advertisement
Answer
Option 1
One way to do that is to cast to the type int
as follows
JavaScript
1
12
12
1
df[['A', 'B']] = df[['A', 'B']].astype(int)
2
3
[Out]:
4
5
Date A B
6
0 01-01-2022 12 0
7
1 02-01-2022 3 123
8
2 03-01-2022 6 23
9
3 04-01-2022 2 0
10
4 05-01-2022 3 0
11
5 06-01-2022 1 12
12
Option 2
One can also do it with .applymap()
as follows
JavaScript
1
12
12
1
df[['A', 'B']] = df[['A', 'B']].applymap(int)
2
3
[Out]:
4
5
Date A B
6
0 01-01-2022 12 0
7
1 02-01-2022 3 123
8
2 03-01-2022 6 23
9
3 04-01-2022 2 0
10
4 05-01-2022 3 0
11
5 06-01-2022 1 12
12
Or using custom lambda functions
JavaScript
1
12
12
1
df[['A', 'B']] = df[['A', 'B']].applymap(lambda x: int(x))
2
3
[Out]:
4
5
Date A B
6
0 01-01-2022 12 0
7
1 02-01-2022 3 123
8
2 03-01-2022 6 23
9
3 04-01-2022 2 0
10
4 05-01-2022 3 0
11
5 06-01-2022 1 12
12
Option 3
Another way is using .apply()
with a custom lambda function
JavaScript
1
12
12
1
df[['A', 'B']] = df[['A', 'B']].apply(lambda x: x.astype(int))
2
3
[Out]:
4
5
Date A B
6
0 01-01-2022 12 0
7
1 02-01-2022 3 123
8
2 03-01-2022 6 23
9
3 04-01-2022 2 0
10
4 05-01-2022 3 0
11
5 06-01-2022 1 12
12