Pandas 如何将txt读入数据帧
我试图将一些web txt数据读入数据框,但我一直遇到“多字符分隔符”问题。以下是数据链接:Pandas 如何将txt读入数据帧,pandas,python-3.7,Pandas,Python 3.7,我试图将一些web txt数据读入数据框,但我一直遇到“多字符分隔符”问题。以下是数据链接: 从urllib.request导入urlretrieve 作为pd进口熊猫 url='1〕https://ticdata.treasury.gov/Publish/mfh.txt' urlretrieve(url,'US Treasurys Holders.txt') 名称=[2019年7月、2019年6月、2019年5月、2019年4月、2019年3月、2019年2月、2019年1月、2018年12月
从urllib.request导入urlretrieve
作为pd进口熊猫
url='1〕https://ticdata.treasury.gov/Publish/mfh.txt'
urlretrieve(url,'US Treasurys Holders.txt')
名称=[2019年7月、2019年6月、2019年5月、2019年4月、2019年3月、2019年2月、2019年1月、2018年12月、2018年11月],
“2018年10月”、“2018年9月”、“2018年8月”、“2018年7月”]
data=pd.read_csv('US Treasurys Holders.txt',skipfooter=21,engine='python',skiprows=11,names=names)
我使用了sep='\s+',但代码始终显示:
错误可能是由于使用多字符分隔符时忽略了引号
问题源于您试图打开的文件的国家/地区名称中存在空格。尝试使用至少两个空格的分隔符:
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