如何在Python中处理CSV文件

151 阅读7分钟

在Python中处理CSV文件

简介

CSV(Comma Separated Values)是一种基本的表格数据文件格式。大多数程序都会创建CSV文件。它们允许你处理来自电子表格和数据库的数据。例如,表格数据可以导出为CSV文件,并导入电子表格,以分析、绘制或发布数据挖掘结果。

这些文件有几种编程语言的广泛支持。CSV文件可以通过文本文件输入和字符串操作语言直接访问和操作。

先决条件

  • 安装有[Python IDE]。
  • 有一些关于Python编程语言的背景资料。

编写一个 CSV 文件

Python 提供了一个内置的 CSV 模块。这个模块包含两个 CSV 编写类。

  • 使用CSV.writer
  • 使用CSV.DictWriter

使用 csv.writer 类

csv.writer 将数据写入一个CSV文件。默认情况下,用户数据被转化为一个带分隔符的字符串。如果带引号的字段不包括 ,CSV文件对象将无法被识别。\n

要写到一个CSV文件,请使用写作者类。写作者类是csv.Dialect 类的一个子类。csv.Dialect 类提供了一组参数,可以用来定制CSV文件。

  • writerow():这个技术写一个行。这个技术可以创建一个字段行。
  • writerows():这种技术一次写出许多行。这是针对行列表的。

为了说明writerow() 类的使用,让我们创建一个CSV文件样本,student_file.csv ,如下图所示。

import csv
with open('student_file.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(["2021", "Student details"])
    writer.writerow([1, "carteblanche kin", "computer science"])
    writer.writerow([2, "Marion koech", "data science"])
2021, Student details
1, carteblanche kin, computer science
2, Marion koech, data science

为了说明writerows() 类的使用,让我们创建一个CSV文件的样本,student_file.csv ,如下图所示。

import csv
csv_rowlist = [["2021", "Student details"], [1, "carteblanche kin", "computer science"],
               [2, "Marion koech", "data science"]]
with open('protagonist.csv', 'w') as file:
    writer = csv.writer(file)
    writer.writerows(csv_rowlist)

该程序的输出与上面writerow() 的例子相同。

使用csv.DictWriter类

这个类建立了一个列到字典的写入对象。这个类支持两种CSV写作方法。它们是

  • writeheader():一个简单的CSV文件,用你选择的字段名发布第一行。

  • writerows():writerows 函数写出所有只有数值的行。

读取一个CSV文件

CSV模块或pandas库可以读取CSV文件。为了能够读取CSV文件,可以使用下面的方法之一。

使用 csv.reader()。

首先在r 模式下使用open() 函数打开CSV文件(打开文件时指定读取模式),然后使用CSV模块的reader() 方法读取。

with 关键字简化了异常处理并立即结束CSV文件。

使用CSV.DictReader()类。

使用open() 打开 CSV 文件,然后使用 CSV 模块的DictReader 类进行读取,该类的工作方式类似于阅读器,但将 CSV 数据转换为字典。文件的第一行包含了字典的键。

使用pandas.read_csv()方法。

使用pandas库方法来读取CSV文件是很简单的。考虑一下fonteds.csv CSV 文件。这就是用来说明其中一个方法的文件。

Giant file

import pandas
csvFile = pandas.read_csv('fonteds.csv')
print(csvFile)

输出

SCHOOL            CEO         YEAR

0 KU    JACOB MUDAVAI         2010

1 MUST   GARETH JASON         2015

2 MMU   DICKSON NJOGU         2013

从上面的代码来看,import pandas 是用来导入pandas模块的,csvFile = pandas.read_csv('fonteds.csv') 是用来读取fonteds.csv 文件的,print(csvFile) 是用来输出读取的csv文件的。

从一个特定的行读取

这里我们将创建一个具有多行和多列的CSV文件,以说明如何从特定的行中读取。

在你的记事本中输入以下数据并保存为student-data.csv ,创建一个CSV文件。该文件将被用来展示如何操作CSV文件。

RegNo   Name        Course  year-of-study   Department
001     James       BCS     2.1             Computing
002     John        BFF     1.2             IT
003     Christine   BSS     4.2             SPAS
004     Lilian      BCOM    3.1             Business
005     Beth        BIT     2.2             IT

为了读取CSV文件中的特定行,我们使用熊猫库中的read_cv 函数。下面的例子说明了如何从一个特定的行中读取。

# Import pandas 
import pandas as pd
# Specify the file location of our CSV file
data = pd.read_csv('File-location/student-data.csv')
# Extract top four data of the specified rows
print (data[0:4]['year-of-study'])

上述代码将输出以下信息。

0   2.1
1   1.2
2   4.2
3   3.1
Name: Name, dtype: float64

读取一个精确的列

pandas库的read_csv 方法还可以另外读取指定的列。这是用.loc() 多轴索引功能完成的。首先,让我们来看看一个示例程序。这个例子将显示所有行的NameCourse 列。

我们将使用前面例子中的student-data.csv 文件。

# Import the pandas module
import pandas as pd
# Specify the file location of our CSV file
data = pd.read_csv('File-location/student-data.csv')
print (data.loc[:,['Name','Course']])

其输出结果

    Name        Course  
0   James       BCS                  
1   John        BFF                
2   Christine   BSS                
3   Lilian      BCOM               
4   Beth        BIT    

操纵CSV文件

由于你不能在读取CSV文件的同时编辑它,你必须创建一个新的CSV文件并写入它。

我们将使用前面例子中的student-data.csv 文件。

从上面的student-data.csv 文件,数据是用大写字母写的。为了演示如何编辑和保存CSV文件,我们将把文件中的大写字母改为小写字母。

with open('student-data.csv','r') as f:
    with open('lowwer-case.csv','w') as ff:
        ff.write(f.readline())
        ff.write(f.read().lower())

上面的代码创建了一个新的CSV文件,其中的所有字母都被改为小写。

在Python中处理大型CSV文件

当处理CSV数据时,通常是先用pandas把它读进去,然后再对它进行处理和分析。然而,由于内存的限制,在消费者机器上直接将巨大的文件读入pandas可能是困难的(或者不可能)。

虽然将数据从CSV文件加载到数据库中很简单,但在有些情况下,你可能无法访问或不想建立数据库服务器。然而,如果你需要在短时间内查看这些大文件中的数据,这里有一种方法可以使用Python和pandas完成。

使用 pandas.read_csv

大文件可以通过分块读取来处理,在读取下一部分之前对其进行处理。块的大小选项决定了行的数量。该方法返回一个迭代器。在处理时,每次读取文件的一个部分。

要读取一个没有分块的数据集,请使用下面的代码。


import pandas as pd # import pandas module
import numpy as np  # Import numpy module
import time         # import time module

s_time = time.time() # This initilizes time module
df = pd.read_csv("voice.csv") # This captures the time taken to read data from our file 
e_time = time.time()

print("Read without chunks: ", (e_time-s_time), "seconds") # print command is used to output the line specified while e_time-s_time outputs the time in seconds

df.sample(10) # This specifies the time taken, 10 seconds

Output

将多个JSON文件转换为CSV文件

一个JSON文件包含基本的数据结构和JavaScript对象符号(JSON)的对象。最常见的使用情况是在互联网应用和服务器之间发送数据。

一个CSV文件是通过串联、合并或连接几个JSON文件(每个文件中至少有一列是相同的),并将结果保存为一个扁平化的数据框而创建的。下面的例子将帮助你了解该任务的整个过程。

示例程序。

我们将输入两个JSON文件并输出一个CSV。使用的JSON文件是。

first.json file

{
    "NO":{ // Declaring the regestration number of the student
        "001":11,
        "002":12,
        "003":13,
        },
    "Name":{// Declaring the name of the student
        "001":"Kelvin",
        "002":"Dennis",
        "003":"John",
        },
    "Marks":{// Declaring the marks of the student
        "001":80,
        "002":84,
        "003":30,
        },
    "Grade":{// Declaring the grade of the student
        "0011":"A",
        "002":"A",
        "003":"D",
        }
}

second.json file

{
     "NO":{ // Declaring the regestration number of the student
        "001":14,
        "002":15,
        "003":16,
        },
    "Name":{ // Declaring the name of the student
        "001":"Mark",
        "002":"James",
        "003":"Avatar",
        },
    "Marks":{ // Declaring the marks of the student
        "001":55,
        "002":90,
        "003":65,
        },
    "Grade":{ //  Declaring the grade of the student
        "0011":"C",
        "002":"A",
        "003":"B",
        }
}

按照下面的步骤就可以转换

  • 用pandas数据框架加载JSON文件。
  • 合并这些数据框架。
  • 从合并后的数据创建一个CSV文件。

结果显示在代码中。

import pandas as pd
df1 = pd.read_json('first.json')#
print(df1)
df2 = pd.read_json('second.json')
print(df2)
df = pd.concat([df1,df2])
print(df)
df.to_csv("CSV.csv",index=False)
result = pd.read_csv("CSV.csv")
print(result)

输出。

Output

使用CSV文件创建一个数据框架

与excel文件一样,CSV文件包括逗号分隔的值。Pandas是Python的核心数据科学模块。在评估数据时,我们经常处理CSV格式的大数据集。从CSV文件中创建一个pandas数据框架很容易。

一个数据框架可以通过以下方式创建。

  • read_csv() 方法
  • read_table() 方法
  • csv 模块

让我们看看一个使用read_table() 方法的例子。

import pandas as pd
df = pd.read_table("dataframe.csv", delimiter =", ")
print(df.head())

Output

总结

感谢你读到最后。本教程教会了我们如何在 Python 中处理 CSV 文件。我们学习了如何写和读CSV文件,如何处理大的CSV文件,如何将多个JSON文件转换为CSV文件,最后,使用CSV文件创建一个数据框。