我從一個網頁上抓取了資料,現在我想把這些資料可視化。當我試圖分散時,我在plt.scatter(data[x],data[y])處得到錯誤 "NameError: name 'x' is not defined" 。我試著看了一下我從網站上搜刮的代碼和資料,也看了一下我自己的代碼。不知道為什么x和y不能作業。有什么解決辦法嗎?
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from mplsoccer.pitch import Pitch
from pandas.core.indexes.base import Index
text_color = 'w'/span>
data = pd.read_csv(#filename)/span>
fig, ax = plt.subplots(figsize=(13,8.5) #lager figurene[/span]。
fig.set_facecolor('#22312b')
ax.patch.set_facecolor('#22312b')
pitch = Pitch(pitch_color='#aabb97'/span>, line_color='white'/span>)
pitch.draw(ax=ax)
plt.scatter(data[x],data[y])
我正在讀取我的資料的csv檔案是這樣的:
import requests
from bs4 import BeautifulSoup
import json
import pandas as pd
base_url = 'https://understat.com/match/'/span>
match = input('Please enter the match id: ')
url = base_url match
res = requests.get(url)
soup = BeautifulSoup(res.content, 'lxml')
scripts = soup.find_all('script')
strings = scripts[1].string
ind_start = strings.index("('") 2)
ind_end = strings.index("')")
json_data = strings[ind_start:ind_end]
json_data = json_data.encode('utf8').Decode('unicode_escape')
data = json.load(json_data)
團隊 = []
分鐘 = []
xg = []
結果 = []
x = []
y = []
情況 = []
玩家 = []
data_away = data['a']
data_home = data['h']
for index in range(len(data_home))。
for key in data_home[index] 。
if key == 'X'/span>:
x.append(data_home[index][key])
if key == 'Y':
y.append(data_home[index][key])
if key == 'xG':
xg.append(data_home[index][key])
if key == 'h_team'/span>:
team.append(data_home[index][key])
if key == 'result':
result.append(data_home[index][key])
if key == 'situation':
situation.append(data_home[index][key])
if key == 'minute':
minute.append(data_home[index][key])
if key == 'player':
player.append(data_home[index][key])
for index in range(len(data_away))。
for key in data_away[index] 。
if key == 'X'/span>:
x.append(data_away[index][key])
if key == 'Y':
y.append(data_away[index][key])
if key == 'xG':
xg.append(data_away[index][key])
if key == 'a_team':
team.append(data_away[index][key])
if key == 'result':
result.append(data_away[index][key])
if key == 'situation':
situation.append(data_away[index][key])
if key == 'minute':
minute.append(data_away[index][key])
if key == 'player':
player.append(data_away[index][key])
col_names = ['Minute','Player','Situation','Team', 'xG','Result','x-coordinate','y-coordinate']
df = pd.DataFrame([minute,player,situation,team,xg,result,x,y], index=col_names)
df.to_csv('shotmaps.csv', encoding='utf-8')
df = df.T
這是我的資料框架
。 未命名。0 0 1 ... 30 31 32 ...
0 Minute 8 10 ... 78 79 86 ...
1 球員克里斯蒂亞諾-羅納爾多 Cristiano Ronaldo ... 阿蘭-圣馬克西明 喬-威洛克 喬林頓
2 情況 OpenPlay OpenPlay ... 開放式游戲 來自角落的開放式游戲
3 Team Manchester United Manchester United ... 紐卡斯爾聯隊 紐卡斯爾聯隊 紐卡斯爾聯隊
4 xG 0.05710771679878235 0.03967716544866562 ... 0.020885728299617767 0.013165773823857307 0.05987533554434776
5 結果MissedShots 失敗球 ... 被阻擋的射門 被救的射門 失敗的射門
6 x坐標 0.9780000305175781 0.9719999694824218 ... 0.7390000152587891 0.705999984741211 0.9119999694824219
7 y坐標 0.33799999237060546 0.72 ... 0.47900001525878905 0.4640000152587891 0.5929999923706055
錯誤資訊
檔案"C:Users#nameAppDataLocalProgramsPythonCodingPacklibsite-packagespandascoreindexesase。 py",第2889,in get_loc
return self._engine.get_loc(casted_key)
檔案 "pandas\_libsindex.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc
檔案 "pandas\_libsindex.pyx", 行 97, in pandas._libs.index.indexEngine.get_loc
檔案 "pandas_libshashtable_class_helper.px", 行 1675, in pandas._libs.hashtable.PyObjectHashTable.get_item
檔案"pandas_libshashtable_class_helper.px",第1683,in pandas._libs.hashtable.PyObjectHashTable.get_item
鑰匙錯誤。'x-coordinate'/span>
上述例外是導致以下例外的直接原因。
回溯(最近一次呼叫)。
檔案"#filename",行19,in<module>
plt.scatter(data['x-coordinate'],data['y-coordinate'] )
檔案 "#filename", line 2899, in __getitem__
indexer = self.columns.get_loc(key)
檔案 "#filename", line 2891, in get_loc
raise KeyError(key) from err
KeyError。'x-coordinate'
uj5u.com熱心網友回復:
僅僅因為一個變數被定義在你運行的檔案中,并不意味著它在你后來運行的另一個檔案中自動可用。你需要以某種方式傳遞它們,例如第二個檔案匯入并在第一個檔案中呼叫一個函式,回傳你要找的值。
然而,這個特殊問題的解決方案要簡單得多。在你的繪圖器檔案中,只需改變
plt.scatter(data[x],data[y])
to
plt.scatter(data["x-coordinate"],data["y-coordinate"] )
這就使用了資料框架的命名列中的資料,這就是你真正想要的。
編輯
上面的修復方法是可行的,但在搜刮代碼的末尾有一個簡單的問題:
EDIT
上面的修復方法是可行的,但在搜刮代碼的末尾有一個簡單的問題
df.to_csv('shotmaps.csv'/span>, encoding='utf-8')
df = df.T
你正在將df保存為CSV,然后將其轉置。把這兩行換一下,在繪圖檔案中使用我上面的代碼,你應該就可以了。我沒有安裝mplsoccer,所以我只是注釋了這些行。
df應該看起來像下面的例子,用id 14620創建 。
# display(df.head())
分鐘球員情況球隊xG結果x-坐標y-坐標
0 13 Roberto Firmino OpenPlay Liverpool 0. 03234297037124634 BlockedShot 0.774000015258789 0.43
1 13 Andrew Robertson OpenPlay Liverpool 0. 03856334835290909MissedShots 0.8830000305175781 0.6880000305175781
2 16 Roberto Firmino OpenPlay Liverpool 0。 07978218793869019MissedShots 0.835 0.509000015258789。
3 20 Xherdan Shaqiri OpenPlay Liverpool 0. 04507734999060631 BlockedShot 0.7919999694824219 0.48900001525878906
4 21 Roberto Firmino OpenPlay Liverpool 0。 09094344824552536 BlockedShot 0.9009999847412109 0.639000015258789
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/312402.html
標籤:
上一篇:在主視窗工具列中嵌入matplotlib與自定義導航工具列動作
下一篇:我怎樣才能把網路服務的輸出分開?
