如何将值附加到现有的逗号分隔csv(excel)fi

2024-03-29 10:27:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个现有的CSV文件,有4列(逗号分隔,所以excel中的所有值都在一列中) enter image description here

如何编写代码,将值“10”添加到每一行(即长度)
另外,如何向这些行添加字符串?

理想的输出是:
enter image description here


我试过了

a = np.array([2,5])
b = np.array([1000,3000])
c = np.array([10])
d = np.array(["both"])

combined = np.array(list(zip(a,b,c,d)))

-- output of combined: --
array([['2', '1000', '10', 'both']], dtype='<U11')

当我使用np.savetxt时,我会遇到这样的错误消息:

np.savetxt("testfile.csv", combined, delimiter=",")  

Error:
Mismatch between array dtype ('<U11') and format specifier

有人能找到解决办法吗?我需要格式化np.savetxt吗?如果是,那么需要补充什么?谢谢


Tags: 文件csv字符串代码npexcelarray逗号
1条回答
网友
1楼 · 发布于 2024-03-29 10:27:02

由于数组的混合类型,在刷新到文件时需要指定格式化程序:

尝试:

np.savetxt("testfile.csv", combined, fmt='%s',delimiter=",")  

在写之前,每个条目都被转换成一个字符串

要解决评论中的问题:

a = np.array([2,5])
b = np.array([1000,3000])
c = np.array([10]*2)
d = np.array(["both"]*2)

这应该给你两排

相关问题 更多 >