How to convert an Object to integer in Pyton 3?

Asked

Viewed 189 times

2

I imported some data in Wikipedia and imported to Pyton. However the data that were to be integer is in the form of Object as in the image below.inserir a descrição da imagem aqui

import pandas as pd 
import requests

url = "https://en.wikipedia.org/wiki/List_of_FIFA_World_Cup_finals"
resposta = requests.get(url)
table = pd.read_html(resposta.text)
resposta = requests.get(url)
df = table[0]
df.head()

I used the command df["Público Pagante"] = df["Público Pagante"].str.replace("[7]","").astype(int). Basically I wanted to take out this [7] and this (.). I think by doing this the variable will turn into whole. But, I don’t know how it does.

1 answer

2

The problem in the substitution happens because, by default, the call df.str.replace considers the first argument to be a regular expression, therefore it is necessary to put a character escape before the clasps ('[' and ']').

The words are amended:

df["Público Pagante"].str.replace("\[7\]", "")

Another option is to specify replace that the first argument is not a regular expression, adding regex = False in charge:

df["Público Pagante"].str.replace("[7]", "", regex=False)

To remove the thousand separator ('.') and convert to whole, add another replace in the expression and convert with the command astype:

df["Público Pagante"].str.replace("[7]", "", regex=False).str.replace(".", "", regex=False).astype(int)

Follow the final result of the command:

In [27]: df["Público Pagante"].str.replace("[7]", "", regex=False).str.replace(".", "").astype(int)
Out[27]:
0      68346
1      55000
...
19     84490
20     78011
Name: Público Pagante, dtype: int32

Browser other questions tagged

You are not signed in. Login or sign up in order to post.