Home > OS >  Python write series object into csv file
Python write series object into csv file

Time:06-09

I have the following two 'Series' objects, which I want to write into a normal csv file with two columns (date and value): enter image description here

However, with my code (see below) I only managed to include the value, but not the date with it: enter image description here

Help would be greatly appreciated!

Best, Lena

CodePudding user response:

You could create a Pandas Dataframe for each of the series, and use the export to csv function of the dataframe. Like this:

import pandas as pd
hailarea_south = pd.DataFrame(hailarea_south)
hailarea_south.to_csv("hailarea_south.csv")

CodePudding user response:

I suggest using pandas.write_csv since it handles most of the things you're currently doing manually. For this approach, however, a DataFrame is easiest to handle, so we need to convert first.

import numpy as np
import pandas as pd


# setup mockdata for example
north = pd.Series({'2002-04-01': 0, '2002-04-02': 0, '2021-09-28': 167})
south = pd.Series({'2002-04-01': 0, '2002-04-02': 0, '2021-09-28': 0})

# convert series to DataFrame
df = pd.DataFrame(data={'POH>=80_south': south, 'POH>=80_north': north})

# save as csv
df.to_csv('timeseries_POH.csv', index_label='date')

output:

date,POH>=80_south,POH>=80_north
2002-04-01,0,0
2002-04-02,0,0
2021-09-28,0,167

In case you want different separators, quotes or the like, please refer to this documentation for further reading.

  • Related