这回咱们用个pandas库
1.首先先看将列表存储到csv:
代码来自于:https://blog.csdn.net/weixin_43245453/article/details/90054820
import pandas as pd #a和b的长度必须保持一致,否则报错 a = [x for x in range(5)] print(a) b = [x for x in range(5,10)] #字典中的key值即为csv中列名 dataframe = pd.DataFrame({‘a_name‘:a,‘b_name‘:b}) print(dataframe) #将DataFrame存储为csv,index表示是否显示行名,default=True dataframe.to_csv(r"test.csv",sep=‘,‘)
#结果: [0, 1, 2, 3, 4] a_name b_name 0 0 5 1 1 6 2 2 7 3 3 8 4 4 9 #text.csv a_name b_name 0 0 5 1 1 6 2 2 7 3 3 8 4 4 9
比上回简单多了吧,真的的贫穷(知识储备)限制了我的想象!!!哈哈
2.接着,我们开始读取:
import pandas as pd from matplotlib import pyplot as plt f = open(‘test.csv‘,encoding = ‘UTF-8‘) data=pd.read_csv(f) #将csv文件读入并转化为dataframe形式 print(data) f1 = data[‘a_name‘].values f2 = data[‘b_name‘].values plt.rc(‘grid‘,linestyle=‘:‘,color=‘green‘) plt.scatter(f1,f2,c=‘red‘) plt.grid() plt.show()
Unnamed: 0 a_name b_name 0 0 0 5 1 1 1 6 2 2 2 7 3 3 3 8 4 4 4 9
3.出现以下问题请关闭csv文件:
Traceback (most recent call last): File "C:\Users\Administrator\Desktop\毕设\程序\导入数据\小程序\按列写入csv文件.py", line 11, in <module> dataframe.to_csv(r"test.csv",sep=‘,‘) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\generic.py", line 3020, in to_csv formatter.save() File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\formats\csvs.py", line 157, in save compression=self.compression) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\common.py", line 424, in _get_handle f = open(path_or_buf, mode, encoding=encoding, newline="") PermissionError: [Errno 13] Permission denied: ‘test.csv‘
原文地址:https://www.cnblogs.com/xiao-yu-/p/12591449.html
时间: 2024-10-18 21:32:55