Script simple
import xarray as xr
ds = xr.open_mfdataset("lokasi file/*.nc", combine='by_coords')
ds.to_netcdf("output.nc")
Looping
import netCDF4
import numpy as np
import pandas as pd
date_range = pd.date_range(start='2022-01-31', end='2022-05-06', freq='D')
for single_date in date_range:
date_str = single_date.strftime('%Y%m%d')
date_str1 = single_date.strftime('%d')
date_str2 = single_date.strftime('%m')
file_pattern = f'D:/GSMAP NC 2022/{date_str2}/{date_str1}/{date_str}.nc'
output_file = f'D:/GSMAP NC 2022/{date_str2}/{date_str1}/StametBiak{date_str}.csv'
latitude = -1.15 # specific latitude
longitude = 136.15 # specific longitude
# Open the netCDF4 file and extract the 'rainrate' variable
with netCDF4.Dataset(file_pattern) as f:
rain = f.variables['rainrate']
# Get dimensions assuming 3D: time, latitude, longitude
time_dim, lat_dim, lon_dim = rain.get_dims()
time_var = f.variables[time_dim.name]
times = netCDF4.num2date(time_var[:], time_var.units)
# Find the indices of the specific latitude and longitude
lat_indices = np.where(f.variables[lat_dim.name][:] == latitude)[0]
lon_indices = np.where(f.variables[lon_dim.name][:] == longitude)[0]
# Check if the latitude and longitude exist in the netCDF4 file
if len(lat_indices) == 0:
print(f"The specific latitude {latitude} does not exist in the file.")
exit()
if len(lon_indices) == 0:
print(f"The specific longitude {longitude} does not exist in the file.")
exit()
# Extract the 'rainrate' values for the specific latitude and longitude
specific_rain_values = rain[:, lat_indices, lon_indices]
# Extract the corresponding time values
time_indices = np.tile(np.arange(len(times)), (len(lat_indices), len(lon_indices)))
specific_times = times[time_indices.flatten()]
# Create a DataFrame with the specific latitude, longitude, time, and rainrate values
df = pd.DataFrame({
'time': specific_times,
'latitude': np.repeat(latitude, len(specific_rain_values.flatten())),
'longitude': np.repeat(longitude, len(specific_rain_values.flatten())),
'rain': specific_rain_values.flatten()})
# Write the DataFrame to a CSV file
print(f'Writing data in tabular form to {output_file} (this may take some time)...')
df.to_csv(output_file, index=False)
print('Done')
Menggabungkan dengan memfilter Latitude dan Longitude
import xarray as xr
import glob
# Definisikan rentang latitude dan longitude yang diinginkan (hapus pagarnya bila digunakan)
# lat_min, lat_max = 0, 10
# lon_min, lon_max = 100, 120
base_dir = "base"
output_file = "output.nc"
files = sorted(glob.glob(f"{base_dir}/*.nc"))
# Temukan dan filter file netCDF berdasarkan rentang latitude dan longitude (hapus pagarnya bila digunakan)
#filtered_files = [f for f in files if (f"{lat_min}:{lat_max}" in f) and (f"{lon_min}:{lon_max}" in f)]
print(f'Menggabungkan file (ini mungkin memakan waktu)...')
try:
ds = xr.open_mfdataset(filtered_files, combine='by_coords')
except:
ds = xr.open_mfdataset(files, combine='by_coords')
ds.to_netcdf(output_file)
print('Selesai')