从Python中的txt文件中提取数行/列

问题描述 投票:0回答:3

我是相当新的Python和遇到了一个小,但(似乎是一个)非常困难的问题。

我有一个包含以下内容的txt文件:

-2      2.1     -0.365635756
0       2.4      0.347433737
2       2.5      0.263774619
4       3.5     -0.244930974
6       4.2     -0.004564913

我的目标是某种方式从Python中的文件中提取不同的行/列的列表或数组使用(再一次,我是相当新的这个)。因此,例如,我将如何使列表[-2,0,2,4,6]使用将数据从第一列?

目前,我有我的工作下面的代码:

import numpy as np

with open('Numbers.txt', 'r') as f:
    fcontents = f.read()
    print(fcontents)

x = np.array(fcontents)

这样做的目的是编写使用数组来计算我们的项目说明给予不同变量的程序。

python arrays list numpy extraction
3个回答
0
投票

我没有用numpy的,但如果你想分成列,你可以做这样的事情

col1 = []
col2 = []
col3 = []

with open('Numbers.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)

其输出

['-2', '0', '2', '4', '6']
['2.1', '2.4', '2.5', '3.5', '4.2']
['-0.365635756', '0.347433737', '0.263774619', '-0.244930974', '-0.004564913']

1
投票

这可能是pandas工作:

import pandas as pd

df = pd.read_fwf('Numbers.txt', header=None)
first_col = df[0]

assert first_col.mean() == 2
assert first_col.median() == 2
assert sum(first_col) == 10

参考文献:


0
投票

你可以导入你的数据作为numpy.array

import numpy as np

data = np.genfromtxt('Numbers.txt', unpack=True).T

然后,检索列/行是作为索引那样简单/切片一个numpy.array

print(data[1,:])
print(data[:,1])

这将导致

[ 0.          2.4         0.34743374]
[ 2.1  2.4  2.5  3.5  4.2]
© www.soinside.com 2019 - 2024. All rights reserved.