Search code examples
pythonpandascsvexport-to-csv

When saving to csv using pandas, I get two same databases instead of two separate ones


I am doing some exercise as part of a GIS and Python Course that I am undertaking individually through Git. The exercise is analysis of weather data from two weather stations. Their IDs are spelled USAF and have codes: 29980 and 28450. I have created a "selected" dataframe from the existing one and from that one, I need to select all rows into a variable called kumpula where the USAF code is 29980 and to a variable Rovaniemi where the USAF code is 28450.

I have done this:

kumpula = selected.loc[selected['USAF']==29980]
rovaniemi = selected.loc[selected['USAF']==28450]

That is good. Now, I need to save the kumpula and rovaniemi DataFrame into 'Kumpula_temps_May_Aug_2017.csv' and 'Rovaniemi_temps_May_Aug_2017.csv'. I also need to separate with comma and use only 2 decimals in the floating point number.

Here is my code:

kumpula = "Kumpula_temps_May_Aug_2017.csv"
selected.to_csv(kumpula, sep=',', float_format="%2f")
rovaniemi = "Rovaniemi_temps_May_Aug_2017.csv"
selected.to_csv(rovaniemi, sep=',', float_format="%2f")

This code should work. But, both of the files are the same. They are for rovaniemi, e.g., USAF code is 28450. Am I somehow overwriting "Kumpula_temps_May_Aug_2017.csv".


Solution

  • You need to modify your code as:

    kumpula_df = selected.loc[selected['USAF']==29980]
    rovaniemi_df = selected.loc[selected['USAF']==28450]
    kumpula_df.to_csv("Kumpula.csv", sep=',', float_format="%2f")
    rovaniemi_df.to_csv("rovaniemi.csv", sep=',', float_format="%2f")