python - 打开包含 3 列的 txt 文件,条件是检查第三列是否有 5 的差异,并将该行的第 1 列和第 2 列返回到新的 txt 文件

标签 python python-2.7

我对编码和Python非常陌生,我认为我咬得太多了,但我正在尝试创建一个程序,该程序读取包含3列信息的txt文件,然后获取这些列并列出它们。 然后,我想创建一个条件,将第三列行值与自身上方和下方的行进行比较,如果该值的差异大于 5,它将复制在第 3 列中找到该值的第 1 列和第 2 行,并且将其附加到一个名为“spikes”的新列表中,我希望可以用它创建一个新的单独的 txt 文件。 我的名称为“xyz_test.txt”的 txt 文件值示例:

98015.985   -4922343.462    101.098 
98015.985   -4922343.712    101.098 
98015.985   -4922343.962    101.093 
98015.985   -4922344.212    101.089 
98015.985   -4922344.462    108.09 
98015.985   -4922344.712    101.095 
98015.985   -4922344.962    101.093 
98015.985   -4922345.212    101.083 
98015.985   -4922345.462    101.081 

到目前为止我能得到并弄清楚的内容如下:

 import csv,math listxy = [] listz = [] spikes = [] files =
 list(csv.reader(open('xyz_test.txt', 'rb'), delimiter='\t'))

 for z in files:
     listxy = z[0],z[1]
     listz = z[2]
     print listz

我得到的结果如下:

101.098 
101.098 
101.093 
101.089 
108.09 
101.095 
101.093 
101.083 
101.081

现在我尝试运行一个条件,首先找到列表中的一个数字,其差异大于其上方和下方的数字 5,但不断收到以下错误: “并非所有参数在字符串格式化期间都被转换”
“无法连接‘str’和‘int’对象”

任何人都可以帮我解决这个问题吗?

Thanks for all the help from everyone, learned allot. i have changed the code to fit what i need , here is what i ended up with. still tweaking , have to create something that sorts the values and loop through several txt files but this is what have so far:

from __future__ import print_function


import pandas as pd
# sets dipslay to larger extent
#pd.set_option('display.height', 10000000)
#pd.set_option('display.max_rows', 5000000)
#pd.set_option('display.max_columns', 50)
#pd.set_option('display.width', 10000)

limit = 3
tries = 0

while True:
        print ("----------------------------------------------------")
        spikewell = float(raw_input("Please Enter Parameters: "))
        tries += 1
        if tries == 4:
            print ("----------------------------------------------------")
            print ("Entered incorrectly to many times.....Exiting")
            print ("----------------------------------------------------")
            break
        else:
            if spikewell > 50:
               print ("parameters past limit (20)")
               print ("----------------------------------------------------")
               print (tries)
               continue
            elif spikewell < 0:
               print ("Parameters cant be negative")
               print ("----------------------------------------------------")
               print (tries)
               continue
            else:
               spikewell
               print ("Parameters are set")
               print (spikewell)
               print ("Searching files")
               print ("----------------------------------------------------")





        terrain = "1_tile_test.txt"
        for df in terrain:
            df = pd.read_csv('1_tile_test.txt', sep=r'\s+', names=['____x____  ','____y____  ','____z____'])
# print orginal data frame (for testing)

# get spikes's coordinates
# df['col3'].shift(1) - previous value of the 'col3' column
# df['col3'].shift(-1) - next value of the 'col3' column
            spikes = df.loc[(df['____z____'] - df['____z____'].shift(1) > spikewell) & \
            (df['____z____'] - df['____z____'].shift(-1) > spikewell)]
            wells = df.loc[-((df['____z____'] - df['____z____'].shift(1) > spikewell)) & \
            -((df['____z____'] - df['____z____'].shift(-1)) > -spikewell)]
# print and save spikes

   # print(spikes[['col1', 'col2','col3']])
   # print(spikes2[['col1', 'col2','col3']])
   # print(wells[['col1', 'col2','col3']])
   # print(wells2[['col1', 'col2','col3']])

            spikes[['____x____  ','____y____  ','____z____']].to_csv('spikes.txt', sep='\t', index=False)
            #spikes2[['____x____  ','____y____  ','____z____']].to_csv('spikes.txt', sep='\t', index=False)
            wells[['____x____  ','____y____  ','____z____']].to_csv('wells.txt', sep='\t', index=False)
            #wells2[['____x____  ','____y____  ','____z____']].to_csv('wells.txt', sep='\t', index=False)
            print ("----------------------------------------------------")
            print ('Search completed')
            break

        break

最佳答案

这是一个例子:

import csv

def is_spike(three):
    first, second, third = three
    return abs(float(first[2]) - float(second[2])) > 5 and abs(float(second[2]) - float(third[2])) > 5

with open("yourcsvfile.csv") as csvfile:
    reader = csv.reader(csvfile)
    rows = list(reader)
    threes = zip(rows, rows[1:], rows[2:])
    spikes = [three for three in threes if is_spike(three)]

print spikes

输出(中间行是“尖峰”):

[(['98015.985', '-4922344.212', '101.089'], ['98015.985', '-4922344.462', '108.09'], ['98015.985', '-4922344.712', '101.095'])]

演练:

首先,我们使用 csv 模块读取整行数据,该模块为我们拆分数据。确保正确设置分隔符。您也可以手动阅读它们,但这更通用。

其次,我们压缩所有三个(如三行),并使用相当简单的is_spike函数检查它们是否形成“尖峰”。

祝你好运。

关于python - 打开包含 3 列的 txt 文件,条件是检查第三列是否有 5 的差异,并将该行的第 1 列和第 2 列返回到新的 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35722689/

相关文章:

python - 将 Unicode 字符串转换为汉字

python-2.7 - python错误无法从python打开应用程序中的pdf

python - App Engine python 上用于 PayPal 网络支付标准的加密 PayPal 按钮?

用于快速、无缝循环许多短音轨的 Python 音频库

Python:如何判断我的 Python 是否具有 SSL?

python - 从相对路径导入模块

python - 字典数据未正确附加到另一个字典

python - 执行 list.pop() 时出现意外结果?

java - 我如何才能知道是否有人正在使用 Python 或 Java 积极使用 Linux 计算机?

python - 在类函数内部定义类函数 : Python