Python Forum
Save data frame to .csv df.to.csv() - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Save data frame to .csv df.to.csv() (/thread-36266.html)



Save data frame to .csv df.to.csv() - mcva - Feb-03-2022

Hi everyone

I need to write a .csv file at each iteration of the following loop. I need to change the name of the .csv file at each iteration. The name of the file at each iteration is stored in the variable location. I´m getting this error: [Errno 2] No such file or directory: 'PONTE AGROAL (15G/02).csv'.
Can someone help me with this problem?
Thank you


f
from netCDF4 import Dataset
import numpy as np
import pandas as pd

# Reading the netcdf file
data = Dataset (r'G:\My Drive\Python_Projects\NC4 Files code\ERA5-Land hourly rad data from 1950 to present\ERA5_Surface solar radiation downwards_1980_2021.nc')
data_range = pd.date_range(start = '1980-01-01', end = '2022-01-01', freq='H')

location_lat_long = pd.read_csv('Stations_location.csv')

for index, row in location_lat_long.iterrows():
    location = row['Name']
    location_latitude = row['Latitude']
    location_longitude = row['Longitude']

    lat = data.variables['latitude'][:]
    lon = data.variables['longitude'][:]

    sq_diff_lat = (lat - location_latitude)**2
    sq_diff_lon = (lon - location_longitude)**2

    #Identifying the index of the minimum value for lat and lon
    min_index_lat = sq_diff_lat.argmin()
    min_index_lon = sq_diff_lon.argmin()


    df1 = pd.DataFrame(0, columns = ['ssrd'], index = data_range)

    df = df1.iloc[:-1 , :]

    dt = np.arange(0, data.variables['time'].size)

    temperature = data.variables['ssrd']

    for time_index in dt:
        df.iloc[time_index] = temperature[time_index, min_index_lat,min_index_lon]
        print (time_index)
    
    #Saving the time series to csv
    df.to_csv(location + '.csv')



RE: Save data frame to .csv df.to.csv() - mcva - Feb-03-2022

I have found this solution.

Replacing the last line with:

df.to_csv(f'Station_{index+1}.csv')
I will get:

Station_1.csv
Station_2.csv


It is not perfect because I still can´t use the name that is stored in

 location = row['Name']
, but it solves the problem.