简体   繁体   English

How can an array be added as a separate column to a CSV file using numpy (preferable) or python 3 without overwriting the CSV file or data?

[英]How can an array be added as a separate column to a CSV file using numpy (preferable) or python 3 without overwriting the CSV file or data?

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

@kinshukdua's comment suggestion as code: @kinshukdua 的评论建议代码:

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. 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)

df.to_csv(file_path, index=False) df.to_csv(file_path, index=False)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM