【问题标题】:Extracting columns of data using python使用python提取数据列
【发布时间】: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 提取这些列?

【问题讨论】:

标签: python pandas dataframe text-parsing


【解决方案1】:

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

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

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

祝你好运

【讨论】:

  • 这行得通!只是我不得不将其更改为sep='\t'
猜你喜欢
  • 2021-06-24
  • 2021-05-29
  • 2022-11-21
  • 2021-05-22
  • 2020-03-19
  • 2016-04-03
  • 2021-10-09
  • 1970-01-01
  • 2021-08-19
相关资源
最近更新 更多