Removing a decimal point in a framework with numbers and strings using Python

I have a data frame with about 50,000 records; and I noticed that “.0” is added behind all the numbers in the column. I am trying to remove the ".0", so the table below;

N  | Movies              
1  | Save the Last Dance 
2  | Love and Other Drugs
3  | Dance with Me      
4  | Love Actually       
5  | High School Musical
6  | 2012.0      <-----
7  | Iron Man     
8  | 300.0       <-----
9  | Inception      
10 | 360.0       <-----
11 | Pulp Fiction

It will look like this:

N  | Movies              
1  | Save the Last Dance 
2  | Love and Other Drugs
3  | Dance with Me      
4  | Love Actually       
5  | High School Musical
6  | 2012     <-----
7  | Iron Man     
8  | 300      <-----
9  | Inception      
10 | 360      <----- 
11 | Pulp Fiction

The problem is that the column contains both numbers and rows.

Is it possible, if so, how?

Thanks in advance.

+4
source share
3 answers

Use the function and apply to the whole column:

In [94]:

df = pd.DataFrame({'Movies':['Save the last dance', '2012.0']})
df
Out[94]:
                Movies
0  Save the last dance
1               2012.0

[2 rows x 1 columns]

In [95]:

def trim_fraction(text):
    if '.0' in text:
        return text[:text.rfind('.0')]
    return text

df.Movies = df.Movies.apply(trim_fraction)

In [96]:

df
Out[96]:
                Movies
0  Save the last dance
1                 2012

[2 rows x 1 columns]
+4
source

Here is a hint

In case of a valid number

a="2012.0"
try:
    a=float(a)
    a=int(a)
    print a

except:
    print a

Output:

2012

In the case of String, like "Dance with Me"

a="Dance with Me"
try:
    a=float(a)
    a=int(a)
    print a

except:
    print a

Output:

Dance with Me
0
source
Python 2.7.2+ (default, Jul 20 2012, 22:15:08) 
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> str1 = "300.0"
>>> str(int(float(str1)))
'300'
>>> 
0
source

Source: https://habr.com/ru/post/1535896/


All Articles