How do I write series to specific existing column in csv file?

Question:

Thank you very much for your time and help.
I have a pandas series named Lon_count, now I want to write it to existing column named stationLon in a csv file read by filepath. I tried

filepath_10ormore =  r'path.csv'
df2 = pd.read_csv(filepath_10ormore)
...
Lon_count.to_csv(filepath_10ormore,float_format="%.4f",columns= 'stationLon',mode='w')

and get KeyError: "None of [Index(['s', 't', 'a', 't', 'i', 'o', 'n', 'L', 'o', 'n'], dtype='object')] are in the [columns]". But I do have the column ‘stationLon’ in the file of filepath_10ormore, and I have closed the file before I run .to_csv()

Lon_count is pandas series, like below. I didn’t show df2 in order to short the code, as I did run the part before the line writing Lon_count to csv file successfully.

Index values

1.2345 4

1.2346 2

1.2347 7

Asked By: Rookie

||

Answers:

The columns argument expects a sequence (usually a list) of column names. You’re specifying a string, so it tries to iterate that sequence, looking for columns named "s", "t", etc.

Try including the column name in a list, like this:

Lon_count.to_csv(filepath_10ormore,float_format="%.4f",columns= ['stationLon'],mode='w')
Answered By: sj95126
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.