【问题标题】:Python: extract position-dependent strings from .txt and save them to different columns of a dataframePython:从 .txt 中提取与位置相关的字符串并将它们保存到数据框的不同列中
【发布时间】:2022-08-10 18:28:29
【问题描述】:

我有一个 .txt 文件 (output.txt),我想从中使用特定的字符串。所需的字符串从位置 13 开始,一直到行尾。我想将它们保存到数据框的不同列中。

我创建了一个包含 4 列的空数据框:

cameras = pd.DataFrame(columns=[\'name\', \'altitude\', \'latitude\', \'longitude\']) 
 

我试图将字符串分配给不同的列

with open(\'output.txt\',\'r\') as f:
        for line in f.readlines():
            if line.startswith(\'name\'):
                cameras[\'name\'] = line[13:-1]
            if line.startswith(\'NN\'):
                cameras[\'altitude\'] = line[13:-1]
            if line.startswith(\'lat\'):
                cameras[\'latitude\'] = line[13:-1]
            if line.startswith(\'lon\'):
                cameras[\'longitude\'] = line[13:-1]

但显然数据框仍然是空的。我想这是一个更容易解决的问题。 提前致谢!

  • 你应该看看read_fwf。将文件读取为两列,将索引设置为index // 4 并进行透视。在您的代码中,您不会追加新行,而是一遍又一遍地覆盖同一行。

标签: python pandas string dataframe readlines


【解决方案1】:

您可以将数据创建为 (<name>, <altitude>, <latitude>, <longitude>) 形式的元组数组。

然后使用pd.from_records() 创建数据框。

这里有几个你应该注意的陷阱。假设输入数据是按“名称”、“高度”、“纬度”、“经度”顺序排列的行。如果顺序中断(由于缺少行或顺序不正确),您将遇到数据不一致的情况。进行严格的数据验证。

请参考https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.from_records.html

【讨论】:

    猜你喜欢
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多