【问题标题】:Extracting rows/columns of numbers from a txt file in Python从Python中的txt文件中提取数字的行/列
【发布时间】:2017-09-16 06:01:28
【问题描述】:

我对 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


【解决方案1】:

我没有用过 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']

【讨论】:

    【解决方案2】:

    这可能是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
    

    参考资料:

    【讨论】:

    • 耶!熊猫规则!但是对于这种特殊的文件格式,我会使用pd.read_fwf()
    【解决方案3】:

    您可以将数据导入为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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-16
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      • 2020-11-26
      相关资源
      最近更新 更多