How to extract the decimal number part from a float (float64) in a dataframe? (a very common scenario but I can 't find a solution in StackOverFlow)
Note: be careful with the 196.09
, I need 09
, not 9
.
Sample DataFrame:
dollars Count
0 56.46 2
1 196.09 3
2 78.12 2
Expected result is the 2 decimal digits:
decimal
0 46
1 09
2 12
float_format to "{:,. 2f}". format to display float values to two decimal places.
The float data type has only 6-7 decimal digits of precision. That means the total number of digits, not the number to the right of the decimal point. Unlike other platforms, where you can get more precision by using a double (e.g. up to 15 digits), on the Arduino, double is the same size as float.
round() function is used to round a DataFrame to a variable number of decimal places. This function provides the flexibility to round different columns by different places.
Use numpy.modf
, multiple by 100
and cast to integer
s:
df['decimal'] = (np.modf(df['dollars'])[0] * 100).astype(int)
Or split
by .
:
df['decimal'] = df['dollars'].astype(str).str.split('.').str[1].astype(int)
print (df)
dollars Count decimal
0 56.46 2 46
1 196.69 3 68
2 78.12 2 12
EDIT: If need 09
format need second solution - output is string
s:
df['decimal'] = df['dollars'].astype(str).str.split('.').str[1]
print (df)
dollars Count decimal
0 56.46 2 46
1 196.09 3 09
2 78.12 2 12
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With