Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python get decimal number from float64 in a dataframe

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
like image 929
Learn Avatar asked Aug 01 '18 16:08

Learn


People also ask

How do you get 2 decimal places on pandas?

float_format to "{:,. 2f}". format to display float values to two decimal places.

Can a float hold a decimal?

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.

How do you round off a column in a data frame?

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.


1 Answers

Use numpy.modf, multiple by 100 and cast to integers:

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 strings:

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
like image 53
jezrael Avatar answered Sep 16 '22 11:09

jezrael