Skip to main content
 首页 » 编程设计

python之将txt格式的url下载到pandas dataframe

2024年10月01日6kenshinobiy

我在尝试从此特定 URL 下载数据并将其存储在 pandas 数据框中时遇到问题。有人能帮忙吗?

url ='http://www2.conectiv.com/cpd/tps/archives/nj/2017/12/20171205NJA1.txt' 

我需要将每个 Segment 存储为一行,并将相应的数字存储在单独的列中。所以,我需要这种格式:

NJAAP, 12/5/2017, 37.63, 36.34, 35.97,..., 38.52 
NJAAS, 12/5/2017, 37.63, 36.34, ...        etc 

我尝试了以下方法:

import pandas as pd 
from urllib.request import urlopen 
 
df = pd.read_csv(url, skiprows=4)  

但是,我没有得到我想要的。我得到这个:

Segment:NJAAP 12/05/2017 37.63 36.34 35.97 35.76 36.71 39.90 46.36 52.49 56.16 58.41 58.98 59.60 59.58 58.52 57.40 54.34 53.90 53.15 51.44 49.49 46.96 44.12 41.02 38.52 
0   Segment:NJAAS 12/05/2017 ... 
1   Segment:NJADC 12/05/2017 ... 
2   Segment:NJAGN 12/05/2017 ... 
3   Segment:NJAGT 12/05/2017 ... 

有人可以帮忙吗?谢谢

请您参考如下方法:

read_csv()有很多有用的选项

  • header=None - 第一行不被视为标题。
  • sep='\s+' - 它使用空格分隔列(而不是逗号 ,)。它是正则表达式。

.

import pandas as pd 
 
url ='http://www2.conectiv.com/cpd/tps/archives/nj/2017/12/20171205NJA1.txt' 
df = pd.read_csv(url, skiprows=4, header=None, sep='\s+') 

加载数据后,您可以更改列中的值。

这将删除第一列中的 Segments:

df[0] = df[0].str.replace('Segment:', '')