将带有NaNs的Numpy数组写入python中的CSV中 [英] Writing Numpy Array with NaNs into CSV in python
本文介绍了将带有NaNs的Numpy数组写入python中的CSV中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用np.savetxt
将2D numpy array
写入csv文件.
I am trying to write 2D numpy array
into csv file using np.savetxt
.
import numpy as np
data = np.array([[0,np.nan,2,3],[4,5,np.nan,7],[8,9,10,np.nan]])
np.savetxt("file.csv", data, delimiter=",", fmt='%.2f')
将创建具有以下内容的文件file.csv
.
Which creates a file file.csv
with the following content.
0.00,nan,2.00,3.00
4.00,5.00,nan,7.00
8.00,9.00,10.00,nan
如您所见,该文件包含nan
而不是空白.我知道nan不是字符串.
As you can see the file contains nan
instead of blanks. I know nan is not a string.
预期输出:
0.00,,2.00,3.00
4.00,5.00,,7.00
8.00,9.00,10.00,
使用pandas
我可以像下面这样实现.
Using pandas
I can achieve this like below.
import pandas as pd
df = pd.DataFrame(data)
df.to_csv("file1.csv", index=False)
但是我暂时不使用pandas
.那么可以使用numpy
做到这一点吗?
But I'm refraining from using pandas
for now. So is it possible to achieve this using numpy
?
推荐答案
最直接的解决方案:
data1 = data.astype(str)
data1[data1=='nan'] = ''
np.savetxt("file.csv", data1, delimiter=",", fmt="%s")
这篇关于将带有NaNs的Numpy数组写入python中的CSV中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文