查找X和Y的最小值/最大值,然后使用Python对5000个文本文件进行插值。

huangapple go评论76阅读模式
英文:

Find Min/max for X and Y, then interpolate for 5000 txt files with python

问题

我有这段可以处理单个文件的工作代码:

import pandas as pd
import pygmt

# 导入表格
df = pd.read_table("file1.txt", sep=" ", names=['X', 'Y', 'Z'])

# 最小/最大值
Xmin = df['X'].min()
Xmax = df['X'].max()
Ymin = df['Y'].min()
Ymax = df['Y'].max()

# 使用pyGMT进行网格化
grid = pygmt.surface(data=df, spacing=1, region=[Xmin, Xmax, Ymin, Ymax])

# 导出
grid.to_netcdf('file1.nc')

现在我想要将这段代码重复用于目录中的所有*.txt文件。我该如何做?我尝试编写一个循环,类似于:

for file in glob.glob("*.txt"):

但如何让相应的输入(.txt)和输出(.nc)具有相同的名称呢?

英文:

I have this working code to process a single file:

import pandas as pd
import pygmt

#import table
df = pd.read_table("file1.txt", sep=" ", names=['X', 'Y', 'Z'] ) 

#min/max
Xmin = df['X'].min()
Xmax = df['X'].max()
Ymin = df['Y'].min()
Ymax = df['Y'].max()
#print(Xmin, Xmax)
#print(Ymin, Ymax)

#gridding with pyGMT
grid = pygmt.surface(data=df, spacing=1, region=[Xmin, Xmax, Ymin, Ymax]) 

#print(grid) 
#export
grid.to_netcdf('file1.nc') 

Now I want to repeat this code for all *.txt files in a directory. How can I do that? I tried writing a loop like:

for file in glob.glob("*.txt"):

But how can I make the respective input (.txt) and output (.nc) have the same name?

答案1

得分: 0

如前所述,在评论部分提到,您也可以通过迭代所有的.txt文件名并将它们的格式更改为.nc并保存名称来完成这个任务。

import glob
import pandas as pd
import pygmt

filenames_in = glob.glob("*.txt")

for filename_in in filenames_in:
    filename_out = filename_in.replace('.txt', '.nc')
    # YOUR CODE
    # 导入表格
    df = pd.read_table(filename_in, sep=" ", names=['X', 'Y', 'Z'])

    # 最小/最大值
    Xmin = df['X'].min()
    Xmax = df['X'].max()
    Ymin = df['Y'].min()
    Ymax = df['Y'].max()
    # 打印(Xmin, Xmax)
    # 打印(Ymin, Ymax)

    # 使用pyGMT进行网格化
    grid = pygmt.surface(data=df, spacing=1, region=[Xmin, Xmax, Ymin, Ymax])

    # 打印(grid)
    # 导出
    grid.to_netcdf(filename_out)
英文:

As said before in comment section you also can do it by iterating all .txt filenames and changes their formats to .nc with saving names.

import glob
import pandas as pd
import pygmt

filenames_in = glob.glob("*.txt")

for filename_in in filenames_in:
    filename_out = filename_in.replace('.txt', '.nc')
    # YOUR CODE
    # import table
    df = pd.read_table(filename_in, sep=" ", names=['X', 'Y', 'Z'])

    # min/max
    Xmin = df['X'].min()
    Xmax = df['X'].max()
    Ymin = df['Y'].min()
    Ymax = df['Y'].max()
    # print(Xmin, Xmax)
    # print(Ymin, Ymax)

    # gridding with pyGMT
    grid = pygmt.surface(data=df, spacing=1, region=[Xmin, Xmax, Ymin, Ymax])

    # print(grid)
    # export
    grid.to_netcdf(filename_out)


huangapple
  • 本文由 发表于 2023年6月2日 14:55:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76387813.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定