英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论