Hello, I’m sorry for any mistake in advance.
By using the pandas, the row that is below the [, was put by the Pandas, is the table index, so it does not count, you can remove.
Now, your No2_ibirapuera object is in the following organization,
No2_ibirapuera = Direct object, you do not have direct access to table.
No2_ibirapuera[0] = And your table.
No2_ibirapuera[0][0] = its first column.
No2_ibirapuera0 = your Second Column.
Now only use No2_ibirapuera0[x], to define the argument x, with the value you want.
we will create a function with the conditions:
def condition(var):
if var == "--":
return "--"
if 0 <= var <= 40:
return "Boa"
if 41 <= var <= 80:
return "Moderada"
if 81 <= var <= 120:
return "Ruim"
if 121 <= var <= 200:
return "Muito Ruim"
return "Péssima"
Now pass the data through the function:
for x in range(len(NO2_Ibirapuera[0][0])):
try:
NO2_Ibirapuera[0][1][x] = condition(int(NO2_Ibirapuera[0][0][x]))
except ValueError:
pass
Why Try and except ? Since I have to transform the table data into integer(int), if it is a letter an error will appear, so with except this item will be ignored, going to the next one.
Final code :
import requests
import pandas as pd
from bs4 import BeautifulSoup
url_dados='http://sistemasinter.cetesb.sp.gov.br/Ar/php/ar_dados_horarios_resultado.php'
r = requests.get(url_dados)
payload = {'texData':'27/02/2018',
'selEst':'5/Ibirapuera'}
response = requests.post(url_dados, data=payload)
with open('dados_ibira.html', 'wb') as f:
f.write(response.text.encode("utf8"))
soup = BeautifulSoup(response.content, 'html.parser')
table = soup.find_all('table')[6]
NO2_Ibirapuera = pd.read_html(str(table).replace(",", "."))
def condition(var):
if var == "--":
return "--"
if 0 <= var <= 40:
return "Boa"
if 41 <= var <= 80:
return "Moderada"
if 81 <= var <= 120:
return "Ruim"
if 121 <= var <= 200:
return "Muito Ruim"
return "Péssima"
for x in range(len(NO2_Ibirapuera[0][0])):
try:
NO2_Ibirapuera[0][1][x] = condition(int(NO2_Ibirapuera[0][0][x]))
except ValueError:
pass
print(NO2_Ibirapuera)
# Com isso o if/else é para ser aplicado nessa coluna com as seguintes condições:
#
# 0 - 40 = Boa
# 41 - 80 = Moderada
# 81 - 120 = Ruim
# 121 - 200 = Muito Ruim
# > 200 = Péssima
Vlw, hugs. Any doubt, just ask.