我正在嘗試將字串從以下位置轉換為整數plans_data:
import pandas as pd
from bs4 import BeautifulSoup
import requests
plans_data = pd.DataFrame(columns = ['Country', 'Currency', 'Mobile', 'Basic', 'Standard', 'Premium'])
for index, row in countries_list.iterrows():
country = row['ID']
url = f'https://help.netflix.com/en/node/24926/{country}'
page = requests.get(url)
soup = BeautifulSoup(page.content, "html.parser")
results = soup.find("table", class_="c-table")
try:
plan_country = pd.read_html(results.prettify())[0] #creates a list(!) of dataframe objects
plan_country = plan_country.rename(columns = {'Unnamed: 0':'Currency'})
plan_country = pd.DataFrame(plan_country.iloc[0,:]).transpose()
plans_data = pd.concat([plans_data, plan_country], ignore_index=True)
except AttributeError:
country_name = row['Name']
print(f'No data found for {country_name}.')
plans_data.loc[index, 'Country'] = row['Name']
plans_data
首先,我嘗試使用函式進行傳輸float:
# 1. Here we import pandas
import pandas as pd
# 2. Here we import numpy
import numpy as np
ans_2_1_ = float(plans_data['Basic', 'Standard', 'Premium'])
但是,我總是得到 NameError:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_15368/3072127414.py in <module>
3 # 2. Here we import numpy
4 import numpy as np
----> 5 ans_2_1_ = float(plans_data['Basic', 'Standard', 'Premium'])
NameError: name 'plans_data' is not defined
我怎么解決這個問題?
如果我的代碼不適合我的任務“將字串轉換為整數”,你能告訴我如何轉換嗎?
uj5u.com熱心網友回復:
該錯誤表明第二段代碼不知道是什么plans_data,因此首先確保plans_data在您執行此操作的位置定義它們,即在同一個檔案或同一個 Jupyter 筆記本中
第二個問題是plans_data['Basic', 'Standard', 'Premium']語法無效
第三,可能是您真正的問題,如何將這些列中的值轉換為浮點數。
“基本”、“標準”、“高級”列中的元素是貨幣格式的字串,例如'£ 5.99'. 您可以將它們轉換為浮點數(您需要為每一列執行此操作):
ans_2_1_ = plans_data['Basic'].str[1:].astype(float)
... # same for Standard and Premium
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/433551.html
標籤:Python python-3.x 熊猫 数据框 名称错误
