使用 python 提取数据列

Extracting columns of data using python

我有一个名为 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 提取这些列?

我认为这对你应该有帮助:

data = pd.read_csv('file_name.txt',sep= " ")

这将为您提供数据框,使用 pandas 数据框很容易计算此类问题。

祝你好运