【问题标题】:open txt file with 3 columns ,with a condition to check the 3rd column for difference of 5 and return that row's column 1 and 2 to a new txt file打开包含 3 列的 txt 文件,条件是检查第 3 列的差异是否为 5,并将该行的第 1 列和第 2 列返回到新的 txt 文件
【发布时间】:2016-03-01 12:16:57
【问题描述】:

我对编码和 python 非常陌生,我认为我咬得比我能咀嚼的更多,但我正在尝试创建一个程序来读取包含 3 列信息的 txt 文件,然后获取这些列并列出它们. 然后我想创建一个条件,它将第 3 列的行值与自身上方和下方的行进行比较,如果值的差异大于 5,它将复制第 1 列和第 2 行,其中该值在第 3 列中找到并且将它附加到一个名为 peaks 的新列表中,我希望可以使用它创建一个新的单独的 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' 对象”

谁能帮我解决这个问题。

感谢大家的帮助,学习了分配。我改变了 适合我需要的代码,这就是我最终得到的。仍然 调整,必须创建一些对值和循环进行排序的东西 通过几个 txt 文件,但这是目前为止的内容:

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

【问题讨论】:

  • 您应该提供导致错误的代码。 Not all arguments converted during string formatting 表示有一个字符串格式化操作,cannot concatenate 'str' and 'int' objects 表示有一个连接,这两者都不是你给我们看的代码。
  • 您希望输出中有多少行 - 只有一个具有 column3==108.09 的行?或者您是否还需要上一行和下一行?请提供预期输出的示例。
  • @gmoshkin @MaxU 抱歉,如果在了解所有这些工作原理的情况下提供的信息很少,第 1 列和第 2 列实际上是 (x , y) 坐标,最后一列是 z 值(高度值)。所以基本上我想创建一些东西,在其他点之间找到尖峰示例 108.09,然后返回该点的 x 和 y 坐标。所以最后的输出将在一个名为 peaks 的新 txt 文件中具有特定尖峰 z 值的 x 和 y:98015.985 -4922344.462 希望这会有所帮助

标签: python python-2.7


【解决方案1】:

这是一个例子:

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 模块读取整行数据,该模块为我们拆分它们。确保正确设置分隔符。您也可以手动阅读它们,但这更通用。

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

祝你好运。

【讨论】:

  • @Reut 感谢您的回复!我尝试了您的代码,但一直给我一条错误消息。回溯(最近一次调用最后一次):文件“I:\test\Spike2.py”,第 14 行,在 中尖峰 = [如果 is_spike(三)] 文件“I:\test\Spike2.py”,第 8 行,在 is_spike 返回 abs(float(first[2]) - float(second[2])) > 5 和 abs(float(second[2] ) - float(third[2])) > 5 IndexError: list index out of range >>> 不知道做错了什么。该文件必须是 csv 文件还是可以是 txt 并打开。("file.txt")
【解决方案2】:

你可能想仔细看看pandas

输入数据(出于测试目的,我添加了一行 [col3==111.110]):

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   -4922344.462    111.110 
98015.985   -4922345.462    101.081 

代码:

from __future__ import print_function

import pandas as pd

df = pd.read_csv('data.csv', sep=r'\s+', names=['col1','col2','col3'])
# print orginal data frame (for testing)
print(df)

# 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['col3'] - df['col3'].shift(1) > 5) & (df['col3'] - df['col3'].shift(-1) > 5)]

# print and save spikes
print(spikes[['col1', 'col2']])
spikes[['col1', 'col2']].to_csv('spikes.csv', sep='\t', index=False)

输出:

        col1         col2     col3
0  98015.985 -4922343.462  101.098
1  98015.985 -4922343.712  101.098
2  98015.985 -4922343.962  101.093
3  98015.985 -4922344.212  101.089
4  98015.985 -4922344.462  108.090
5  98015.985 -4922344.712  101.095
6  98015.985 -4922344.962  101.093
7  98015.985 -4922345.212  101.083
8  98015.985 -4922344.462  111.110
9  98015.985 -4922345.462  101.081
        col1         col2
4  98015.985 -4922344.462
8  98015.985 -4922344.462

spikes.csv:

col1    col2
98015.985   -4922344.462
98015.985   -4922344.462

【讨论】:

  • 它说“没有名为 pandas 的模块”
  • @EdwinPage,你必须安装它:“pip install pandas”。 pandas.pydata.org/pandas-docs/stable/install.html
  • @ MaxU,我安装了它!,我运行了一个测试,它工作正常,我在小列表上尝试了一些测试,它很好,前一行和下一行都低于 5,但是来了如果前一行或下一行中的一个不大于 5,则在接缝处发出不拾取尖峰的问题。我尝试将尖峰更改为“if”函数,但告诉我语法无效,并尝试使用“或”代替的“&”,它给了我“一个系列的真值是模棱两可的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。”不知道我错过了什么
  • @EdwinPage,您能否使用不起作用的数据样本更新您的问题?如果你想在 Pandas 的 DataFrame 中使用 OR 而不是 AND ("&"),只需使用 "|"。
猜你喜欢
  • 1970-01-01
  • 2016-10-20
  • 1970-01-01
  • 1970-01-01
  • 2018-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-27
相关资源
最近更新 更多