1. 通过numpy,借助pd保存二维数据到CSV
- 将数组实例化为np.array对象,通过pandas.DataFrame保存为对象,使用其to_csv方法保存为csv文件
import pandas as pd
import numpy as np
li = [['name', 'age', 'addres'],
['john', '18', 'bj'],
['jack', '26', 'sh']]
array = np.array(li)
print(type(array))
print(array)
df = pd.DataFrame(array)
print(type(df))
print(df)
df.to_csv('data.csv')
执行结果:
<class 'numpy.ndarray'>
[['name' 'age' 'addres']
['john' '18' 'bj']
['jack' '26' 'sh']]
<class 'pandas.core.frame.DataFrame'>
0 1 2
0 name age addres
1 john 18 bj
2 jack 26 sh
2. np.savetxt()保存csv
(1)np.savetxt('frame',array,fmt='%d',delimiter=None)
frame: 文件
array:存入文件的数组
fmt:写入文件的格式,如%d %f %e
delimiter:分割字符串,默认空格
import numpy as np
a = np.arange(20).reshape(2, 10)
b = np.savetxt('data/a.csv', a, fmt='%d', delimiter=',')
print(a)
[[ 0 1 2 3 4 5 6 7 8 9]
[10 11 12 13 14 15 16 17 18 19]]
执行结果:

内容:

(2) np.loadtxt('frame',dtype=np.int,delimiter=None,unpack=False)
frame:文件
dtype:数据类型
delimiter:分割字符串
unpack:若为True,则读入属性奖分别写入不同变量
import numpy as np
a = np.arange(20).reshape(2, 10)
b = np.savetxt('data/b.csv', a, fmt='%d', delimiter=',')
c = np.loadtxt('data/b.csv', delimiter=',')
print(c)
[[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
[10. 11. 12. 13. 14. 15. 16. 17. 18. 19.]]
网友评论