我正在尝试将一些Web txt数据读入数据帧,并且一直遇到“多字符分隔符”问题。这是数据的链接:https://ticdata.treasury.gov/Publish/mfh.txt
from urllib.request import urlretrieve
import pandas as pd
url = 'https://ticdata.treasury.gov/Publish/mfh.txt'
urlretrieve(url, 'US Treasurys Holders.txt')
names = ['Jul 2019', 'Jun 2019', 'May 2019', 'Apr 2019', 'Mar 2019', 'Feb 2019', 'Jan 2019', 'Dec 2018', 'Nov 2018',
'Oct 2018', 'Sep 2018', 'Aug 2018', 'Jul 2018']
data = pd.read_csv('US Treasurys Holders.txt', skipfooter=21, engine='python', skiprows=11, names=names)
我使用了sep ='\ s +',但是代码不断向我显示:
错误可能是由于使用多字符定界符时引号被忽略
答案 0 :(得分:1)
问题源于您要打开的文件的国家/地区名称中存在空格。尝试使用至少两个空格的定界符:
data = pd.read_csv(
"US Treasurys Holders.txt",
skipfooter=21,
engine="python",
sep="\s\s+",
skiprows=11,
names=names,
)
哪个给出了我认为正确的输出(这里是5列x 5行的子集):
Jul 2019 Jun 2019 May 2019 Apr 2019 Mar 2019
Japan 1130.8 1122.9 1101.0 1064.0 1078.1
China, Mainland 1110.3 1112.5 1110.2 1113.0 1120.5
United Kingdom 334.7 341.1 323.1 300.8 317.1
Brazil 309.9 311.7 305.7 306.7 311.7
Ireland 258.2 262.1 270.7 269.7 277.6