[英]Error while reading compressed CSV file from URL with pandas.read_csv
[英]Error while reading imported csv file from url with pandas
我是一個初學者,試圖推進我通過教程學到的項目。 該項目包括從美國地質調查局導入一個csv文件並將其數據繪制在地圖上。
我設法使用計算機上的文件來制作它。 但是,我無法直接從url獲取csv,因此數據可以自行更新。
現在我正在使用熊貓並收到此錯誤:
文件“ C:/Users/Felipe/PycharmProjects/earthquake/earthquake.py”,第6行,以open(filename)作為csvfile:TypeError:預期的str,字節或os.PathLike對象,而不是DataFrame
import pandas as pd
filename = pd.read_csv('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_hour.csv')
lats, lons = [], []
with open(filename) as f:
reader = csv.reader(f)
next(reader)
for row in reader:
lats.append(float(row[1]))
lons.append(float(row[2]))
print('lats', lats[0:5])
print('lons', lons[0:5])
這部分代碼是我嘗試檢索de csv文件的地方。
我相信(再次,我是一個初學者),pandas實際上給了我已經“處理過”的數據(不再是csv了),而我嘗試使用的工具可用於csv文件本身(這就是我試圖理解錯誤,我敢肯定我可能是錯的,但是我什么也沒想到。
我嘗試查看熊貓文檔,但找不到有關“ DataFrame”錯誤的很多信息。 導入文件后,我也嘗試使用“ .to_csv”,但是沒有用。
因此,tl; dr如何解決該代碼並導入csv文件並使用其數據?
我還有一些其他問題,找不到答案:在“使用open(filename)as f:”上,“ f”有什么作用?
非常感謝!
我相信文件名應該只是名稱。
filename = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_hour.csv'
這應該將其放入數據框:
import io
import requests
content = requests.get(filename).content
df = pd.read_csv(io.StringIO(content.decode('utf-8')))
或者簡單地:
df = pd.read_csv(filename)
pd.read_csv()
也接受URL並返回已解析的Pandas DataFrame。
演示:
In [55]: url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_hour.csv'
In [56]: df = pd.read_csv(url)
In [57]: df
Out[57]:
time latitude longitude depth mag magType nst gap dmin rms ... updated \
0 2017-09-12T20:38:20.330Z -15.079900 -174.19000 144.26 4.80 mb NaN 71 2.6100 0.85 ... 2017-09-12T20:56:45.040Z
1 2017-09-12T20:22:02.350Z 39.878502 -121.27433 6.78 2.74 md 9.0 215 0.3287 0.14 ... 2017-09-12T20:36:02.917Z
place type horizontalError depthError magError magNst status locationSource magSource
0 107km NNW of Hihifo, Tonga earthquake 8.80 5.30 0.033 285 reviewed us us
1 27km ENE of Magalia, California earthquake 1.82 10.49 0.240 8 automatic nc nc
[2 rows x 22 columns]
In [58]: df[['latitude','longitude']]
Out[58]:
latitude longitude
0 -15.079900 -174.19000
1 39.878502 -121.27433
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.