【问题标题】:Outputting a specific row from a URL从 URL 输出特定行
【发布时间】:2017-04-08 00:35:01
【问题描述】:

这是我使用的网址:

http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.csv

我需要这样输出:

正在从 USGS 下载地震数据 ... 最大规模地震是: 时间:2016-10-17T06:14:58.370Z 纬度:-6.0526 经度:148.8617 位置:巴布亚新几内亚坎德里安西北 78 公里 幅度:6.9 深度:35

我已经有一个读取和解码行的函数 这是一些代码:

def online_display_largest_quake():
 print('Downloading earthquake data from USGS ...')

 earthquakes = get_text_lines_from_url('http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.csv')
 print (earthquakes)
 best_mag = 0
 best_item = []

 for (item) in earthquakes[1:]:

    if float(item[4]) > best_mag:
        best_mag = float(str(item[4]))
        best_item = item

 earthquake_output(best_item) 

【问题讨论】:

  • item 是您输出的变量(因此,item[4] 是 item 中包含的行的第 5 列中的数据)吗?
  • @PyNoob 是一组来自在线 excel 文档的关于不同地震的数据。我想挑选出幅度最大的那个,然后以可读的格式输出整行。所以 item[4] 指的是幅度列,但它实际上是指第 5 个字符,即“-”这是我卡住的地方
  • 也许您可以提供item 的结构和更多代码以获得更量身定制的答案。同时,我提供了一个使用 pandas 的。
  • @PyNoob 我编辑了问题以提供上下文

标签: python csv url formatting


【解决方案1】:

也许您可以发布几行您正在使用的 CSV 和更多代码,让我们更好地了解数据以及您如何进行分析。

我在网上找到了一个 CSV,其中包含我将用于示例的地震数据行。使用 pandas,您可以直接输入 URL 并轻松获取发生最大规模地震的行(我相信这就是您正在做的事情)。

> import pandas as pd

> url = 'http://itp.nyu.edu/~cm2897/blog/wp-content/uploads/2012/03/global-earthquakes.csv'
> df = pd.read_csv(url)
> df.head()
   year  month  day      time  latitude  longitude  magnitude  depth
0  1973      1    1   34609.8     -9.21     150.63        5.3     41
1  1973      1    1   52229.8    -15.01    -173.96        5.0     33
2  1973      1    1  114237.5    -35.51     -16.21        6.0     33
3  1973      1    2    5320.3     -9.85     117.43        5.5     66
4  1973      1    2   22709.2      1.03     126.21        5.4     61

> df.loc[df['magnitude'].idxmax()]
year         2004.00
month          12.00
day            26.00
time         5853.45
latitude        3.30
longitude      95.98
magnitude       9.00
depth          30.00
Name: 48506, dtype: float64

Pandas 的 Series.idxmax 方法返回 Series 中出现最大值的索引(在本例中,是 DataFrame 中的幅度列)。有关更多信息,请参阅this answer。有了这个索引,我们就可以用DataFrame.loc返回对应的行了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 1970-01-01
    • 2016-04-03
    • 2019-04-14
    • 1970-01-01
    相关资源
    最近更新 更多