Add pandas DataFrame column to CSV

I am trying to add a pandas DataFrame (single column) to an existing CSV, like this post , but it does not work! Instead, my column is added at the bottom of csv and iterates over and over (rows in the csv → column). Here is my code:

with open(outputPath, "a") as resultsFile:
    print len(scores)
    scores.to_csv(resultsFile, header=False)
    print resultsFile

Terminal output: 4032 <open file '/Users/alavin/nta/NAB/results/numenta/artificialWithAnomaly/numenta_art_load_balancer_spikes.csv', mode 'a' at 0x1088686f0>

Thank you in advance!

+4
source share
1 answer

As with the @aus_lacy clause, you just need to first read the csv file in the data frame, merge the two data frames and write them back to the csv file:

suggested that your existing data frame is called df :

df_csv = pd.read_csv(outputPath, 'your settings here')

# provided that their lengths match
df_csv['to new column'] = df['from single column']

df_csv.to_csv(outputPath, 'again your settings here')

What is it.

+5
source

Source: https://habr.com/ru/post/1570502/


All Articles