【发布时间】:2020-08-15 03:05:12
【问题描述】:
我有一个名为 data.txt 的文本文件,它看起来像:
n sin(n) cos(n)
0 0 1
1 0.841470985 0.540302306
2 0.909297427 -0.416146837
3 0.141120008 -0.989992497
4 -0.756802495 -0.653643621
5 -0.958924275 0.283662185
6 -0.279415498 0.960170287
7 0.656986599 0.753902254
8 0.989358247 -0.145500034
9 0.412118485 -0.911130262
10 -0.544021111 -0.839071529
我正在尝试将这些数据列提取到 pandas 数据框中。
我现在正在做的是:
col1 = []
col2 = []
col3 = []
with open('data.txt', 'r') as f:
for line in f:
first, second, third = line.split()
col1.append(first)
col2.append(second)
col3.append(third)
print(col1)
print(col2)
print(col3)
这段代码逐行读取data.txt,如果我有巨大的数据文件,它会变得很慢。
有没有办法使用 pandas 之类的东西来简化这个过程?是否可以使用 pandas 提取这些列?
【问题讨论】:
-
看看pandas.pydata.org/pandas-docs/stable/reference/api/… 特别是
sep参数。
标签: python pandas dataframe text-parsing