change :import numpy as np
import xarray as xr
import pandas as pd
from scipy.cluster.hierarchy import fcluster, linkage
import datetime

def main(input_file, output_file, num_clusters, time_file):
# Read the input file
dataset = xr.open_dataset(input_file)
msl = dataset['msl']
time, lat, lon = msl.shape

scheme
Copy
# Select a random sample of data
sample_size = 61
interval = 24
start_index = 0
end_index = start_index + sample_size
sample_indices = []
while end_index <= time:
    sample_indices += list(range(start_index, end_index, 2))
    start_index += interval
    end_index = start_index + sample_size
sample_msl = msl[sample_indices,:,:]

# Reshape the data
reshaped_msl = sample_msl.values.reshape(len(sample_indices), lat * lon)

# Perform hierarchical clustering with Pearson correlation
linkage_matrix = linkage(reshaped_msl.T, method='complete', metric='correlation')
cluster_labels = fcluster(linkage_matrix, num_clusters, criterion='maxclust')

# Calculate the average of each cluster
cluster_means = np.zeros((num_clusters, lat, lon))
cluster_times = {}
for i in range(num_clusters):
    # Create a boolean index array
    bool_index = (cluster_labels == i+1)
    
    # Reshape the boolean index array to match the first dimension of the array being indexed
    bool_index_reshaped = np.reshape(bool_index, (len(bool_index),))
    
    # Index the sample_msl array using the reshaped boolean index array
    cluster_points = sample_msl.values[bool_index_reshaped,:,:]
    
    # Calculate the cluster mean
    cluster_means[i] = np.mean(cluster_points, axis=0)
    
    # Save the time indices of the cluster members
    cluster_times[f'Cluster{i+1}'] = sample_indices[bool_index_reshaped]

# Create the output file
output_dataset = xr.Dataset()

# Add details to the output file
output_dataset.attrs['title']= 'Clustered msl variable'
output_dataset.attrs['institution'] = 'My institution'
output_dataset.attrs['source'] = 'Original data from ' + input_file
output_dataset.attrs['history'] = 'Created on ' + datetime.datetime.now().strftime("%Y-%m-%d %H:%%M:%S")
output_dataset.attrs['description'] = 'Hierarchical clustering with Pearson correlation'
output_dataset.attrs['num_clusters'] = num_clusters

# Create the dimensions
output_dataset['lat'] = ('lat',), dataset['lat'].values
output_dataset['lon'] = ('lon',), dataset['lon'].values
output_dataset['num_clusters'] = ('num_clusters',), np.arange(num_clusters)

# Create the 'msl' variable
output_dataset['msl'] = ('num_clusters', 'lat', 'lon'), cluster_means

# Copy the attributes fromthe input file
output_dataset['msl'].attrs = dataset['msl'].attrs.copy()

# Add the copied attributes to the 'msl' variable
output_dataset.to_netcdf(output_file)

# Save time of each member in each cluster to an Excel file
writer = pd.ExcelWriter(time_file)
for i in range(num_clusters):
    cluster_name = f'Cluster{i+1}'
    cluster_time = cluster_times[cluster_name]
    cluster_time_df = pd.DataFrame({'Time': cluster_time})

    for j in range(num_clusters):
        if i != j:
            col_name = f'Cluster{j+1}'
            other_cluster_time = cluster_times[f'Cluster{j+1}']
            other_cluster_time_df = pd.DataFrame({col_name: other_cluster_time})
            cluster_time_df =pd.merge(cluster_time_df, other_cluster_time_df, how='outer', left_index=True, right_index=True)

    cluster_time_df.to_excel(writer, sheet_name=cluster_name, index=False)
writer.save()
if name == 'main':
input_file = r'C:\Users\admin\Desktop\wavelet.nc'
output_file = r'C:\Users\admin\Desktop\x.nc'
num_clusters = 10
time_file = r'C:\Users\admin\Desktop\cluster_times.xlsx'
main(input_file, output_file, num_clusters, time_file), to remove each part of creating excel file .