0

The new data to be appended has a shorter length!

Here is an example:

Add numpy array:
ema  =  [3.3  3.4  3.5  3.6]

                                            (csv now has 3-columns of equal length)
1.1  2.1    append  ema  to end up with:    1.1  2.1  0
1.2  2.2                                    1.2  2.2  0
1.3  2.3                                    1.3  2.3  3.3
1.4  2.4                                    1.4  2.4  3.4
1.5  2.5                                    1.5  2.5  3.5
1.6  2.6                                    1.6  2.6  3.6
Gulzar
  • 23,452
  • 27
  • 113
  • 201
rn kim
  • 49
  • 4
  • 1
    Best way would be to read the old data as a `pandas` dataframe and then append the column to it and fill empty columns with 0s and finally writing it back to csv. – kinshukdua May 11 '21 at 20:33
  • 1
    A `csv` file is a text file. You can add new lines (rows) to such a file, but you can't add columns without writing a whole new file. Imagine adding material to written text. Unless text has space on to the right of each line, you can only add stuff the bottom (or a new page). – hpaulj May 11 '21 at 23:07

2 Answers2

0

@kinshukdua's comment suggestion as code:

Best way would be to read the old data as a pandas dataframe and then append the column to it and fill empty columns with 0s and finally writing it back to csv.

using this

import pandas as pd
my_csv_path = r"path/to/csv.csv"
df = pd.read_csv(my_csv_path)
ema_padded = np.concatenate([np.zeros(len(df) - ema.shape[0]), ema])
df['ema'] = pd.Series(ema_padded, index=df.index)
df.to_csv(my_csv_path)
Gulzar
  • 23,452
  • 27
  • 113
  • 201
0

df.to_csv(file_path, index=False)

rn kim
  • 49
  • 4