zoukankan      html  css  js  c++  java
  • PYTHON将列表存储为csv文件以及从csv中提取数据2

    这回咱们用个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:UsersAdministratorDesktop毕设程序导入数据小程序按列写入csv文件.py", line 11, in <module>
        dataframe.to_csv(r"test.csv",sep=',')
      File "C:UsersAdministratorAppDataLocalProgramsPythonPython37-32libsite-packagespandascoregeneric.py", line 3020, in to_csv
        formatter.save()
      File "C:UsersAdministratorAppDataLocalProgramsPythonPython37-32libsite-packagespandasioformatscsvs.py", line 157, in save
        compression=self.compression)
      File "C:UsersAdministratorAppDataLocalProgramsPythonPython37-32libsite-packagespandasiocommon.py", line 424, in _get_handle
        f = open(path_or_buf, mode, encoding=encoding, newline="")
    PermissionError: [Errno 13] Permission denied: 'test.csv'
  • 相关阅读:
    oracle实现自增id
    一些.NET 项目中经常使用的类库
    文件读取是判断是否读取到末尾
    文件操作
    第一个html文件
    HTML标签(持续更新)
    配置tomcat
    判断一个String中是否有指定字符或字符串
    去掉字符串中的某个字符
    把一个activity作为弹窗
  • 原文地址:https://www.cnblogs.com/xiao-yu-/p/12591449.html
Copyright © 2011-2022 走看看