Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Remove decimal and zero from string

Tags:

python

pandas

I'm reading several spreadsheets into a data frame and there is an ID field that is a string in some spreadsheets and a number in others. I've converted it into a string, which is the data type I need, but I'm ending up with some IDs that have a ".0" at the end. How do I remove the decimal and zero?

Example: ID number 805096730.0 should be 805096730

like image 710
Dread Avatar asked Oct 16 '17 15:10

Dread


People also ask

How do I remove 0 after decimal in Python?

Use the str() class to convert the decimal to a string. Use the str. rstrip() method to strip the trailing zeros if the number has a decimal point.To remove trailing zeros from a decimal: Use the decimal.

How do I remove a decimal from a string in Python?

Using trunc() Function In the first program, we will make use of trunc() function and remove the decimal present in the numbers.

How do you remove decimals from data labels?

Right click on one of the decimal value on the graph and go to format y/x axis and under number tab you have an option to make the decimal places to 0.


1 Answers

Use astype with replace:

df = pd.DataFrame({'ID':[805096730.0,805096730.0]})

df['ID'] = df['ID'].astype(str).replace('\.0', '', regex=True)
print (df)
          ID
0  805096730
1  805096730

Or add parameter dtype:

df = pd.read_excel(file, dtype={'ID':str})
like image 112
jezrael Avatar answered Sep 27 '22 16:09

jezrael