【发布时间】:2015-11-18 05:27:27
【问题描述】:
我正在使用 pandas 打开一个 txt 文件,文件中应该有一个分栏符的地方有一个 \t 代替。
我正在阅读这样的文件:
df=pd.read_csv(r'file.txt')
数据框如下所示:
1 Band 1\t 0.428944\t0.843916\t0.689923\t0
2 Band 2\t-0.000000\t0.689320\t0.513170\t0
3 Band 3\t 0.336438\t0.743478\t0.592622\t0
4 Band 4\t 0.313259\t0.678561\t0.525667\t0
5 Band 5\t 0.374522\t0.746828\t0.583513\t0
我希望它看起来像这样:
1 Band 1 0.428944 0.843916 0.689923
2 Band 2 -0.000000 0.689320 0.513170
3 Band 3 0.336438 0.743478 0.592622
4 Band 4 0.313259 0.678561 0.525667
5 Band 5 0.374522 0.746828 0.583513
我是在 python 中使用 txt 文件的新手,我可能需要设置某种分隔符吗?
使用print(repr(open(r'D:\Sheyenne\Statistics\NDVI_allotment\Text\A_Annex2.txt').read(42))) 返回:
'\n\n Band 1\t 0.428944\t0.843916\t0.689923\t
编辑:
我发布的原始数据框经过简化,实际上有更多的数据列。
`print(repr(open(r'D:\Sheyenne\Statistics\NDVI_allotment\Text\A_Annex2.csv').read(500)))
返回:
'\nBasic Stats\t Min\t Max\t Mean\t Stdev\t Num\tEigenvalue\n Band 1\t 0.428944\t0.843916\t0.689923\t0.052534\t 1\t 0.229509\n Band 2\t-0.000000\t0.689320\t0.513170\t0.048885\t 2\t 0.119217\n Band 3\t 0.336438\t0.743478\t0.592622\t0.052544\t 3\t 0.059111\n Band 4\t 0.313259\t0.678561\t0.525667\t0.048047\t 4\t 0.051338\n Band 5\t 0.374522\t0.746828\t0.583513\t0.055989\t 5\t 0.027913\n Band 6\t-0.000000\t0.749325\t0.330068\t0.314351\t 6\t 0.022561\n Band 7\t-0.000000\t0.819288\t0.6001'
【问题讨论】:
-
能否也给我们看一份文件样本?
print(repr(open('file.txt').read(100)))在这里会很有帮助。 -
我在 Google 上搜索了您问题的标题,并找到了一些有用的结果,例如 this one(Java,但仍然相关)。
-
@Martijn Pieters,很抱歉,您所说的样本是什么意思?我展示的第一个代码块是它的样例,你的意思是不同的吗?
-
我的意思是不同的;我想看看原始数据。我给了你一个 Python 命令,它会从文件中生成前 100 个字符。
-
返回
'Filename: F:\\Sheyenne\\Atmospherically Corrected Landsat\\Indices\\Main\\NDVI\\NDVI_stack\nROI: EVF: Layer'。但这只是txt文件的第一行