迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 将 CSV 分割成多个文件

作者:迹忆客 最近更新:2023/06/01 浏览次数:

在本文中,我们将学习如何在 Python 中将一个 CSV 文件拆分为多个文件。 我们将使用 Pandas 创建一个 CSV 文件并将其拆分为多个其他文件。


使用 Pandas 在 Python 中创建 CSV 文件

要使用 Pandas 在 Python 中创建 CSV,必须首先通过命令行界面 (CLI) 安装 Pandas。

pip install pandas

此命令将下载 Pandas 并将其安装到您的本地计算机中。 使用 import 关键字,您可以轻松地将其导入到您当前的 Python 程序中。

让我们验证 Pandas 是否已安装。

代码示例:

import pandas as pd
print("The Version of Pandas is: ", pd.__version__)

输出:

The Version of Pandas is: 1.3.5

现在,让我们创建一个 CSV 文件。

代码示例:

import pandas as pd

# create a data set
data_dict = {'Roll no':    [1, 2, 3, 4, 5, 6, 7, 8],

             'Gender': ["Male", "Female", "Female", "Male",
                        "Male", "Female", "Male", "Female"],

             'CGPA':       [3.5, 3.3, 2.7, 3.8, 2.4, 2.1, 2.9, 3.9],

             'English':     [76, 77, 85, 91, 49, 86, 66, 98],

             'Mathematics': [78, 87, 54, 65, 90, 59, 63, 89],

             'Programming': [99, 45, 68, 85, 60, 39, 55, 88]}

# create a data frame
data = pd.DataFrame(data_dict)

# convert the data frame into a csv file
data.to_csv("studesnts.csv")

# Print the output
print(data)

输出:

   Roll no  Gender  CGPA  English  Mathematics  Programming
0        1    Male   3.5       76           78           99
1        2  Female   3.3       77           87           45
2        3  Female   2.7       85           54           68
3        4    Male   3.8       91           65           85
4        5    Male   2.4       49           90           60
5        6  Female   2.1       86           59           39
6        7    Male   2.9       66           63           55
7        8  Female   3.9       98           89           88

在 Python 中将 CSV 文件拆分为多个文件

我们已经成功创建了一个 CSV 文件。 让我们将其拆分为多个文件,但可以使用不同的矩阵在列或行的基础上拆分 CSV。

根据行拆分 CSV 文件

让我们在 Python 中基于行拆分 CSV 文件。

代码示例:

import pandas as pd

# read DataFrame
data = pd.read_csv("students.csv")

# number of csv files along with the row
k = 2
size = 4

for i in range(k):
    df = data[size*i:size*(i+1)]

    df.to_csv(f'students{i+1}.csv', index=False)

file1 = pd.read_csv("students1.csv")
print(file1)
print("\n")
file2 = pd.read_csv("students2.csv")
print(file2)

输出:

      Roll no  Gender  CGPA  English  Mathematics  Programming
0        1    Male     3.5       76           78           99
1        2    Female   3.3       77           87           45
2        3    Female   2.7       85           54           68
3        4    Male     3.8       91           65           85

      Roll no  Gender  CGPA  English  Mathematics  Programming
4        5   Male     2.4       49           90           60
5        6   Female   2.1       86           59           39
6        7   Male     2.9       66           63           55
7        8   Female   3.9       98           89           88

上面的代码将 students.csv 文件拆分为两个多文件,student1.csv 和 student2.csv。 文件按行分隔; 第 0 到 3 行存储在 student.csv 中,第 4 到 7 行存储在 student2.csv 文件中。

根据列拆分 CSV 文件

借助 groupby() 函数,我们可以根据列矩阵拆分任何 CSV 文件。 groupby() 函数属于 Pandas 库,使用分组数据。

在这种情况下,我们根据性别对学生数据进行分组。

代码示例:

import pandas as pd

# read DataFrame
data = pd.read_csv("students.csv")

for (gender), group in data.groupby(['Gender']):
     group.to_csv(f'{gender} students.csv', index=False)

print(pd.read_csv("Male students.csv"))
print("\n")
print(pd.read_csv("Female students.csv"))

输出:

       Roll no  Gender  CGPA  English  Mathematics  Programming
0        1      Male   3.5       76           78           99
1        4      Male   3.8       91           65           85
2        5      Male   2.4       49           90           60
3        7      Male   2.9       66           63           55


       Roll no  Gender  CGPA  English  Mathematics  Programming
0        2      Female   3.3       77           87           45
1        3      Female   2.7       85           54           68
2        6      Female   2.1       86           59           39
3        8      Female   3.9       98           89           88

总结

拆分数据是一种有用的数据分析技术,有助于理解和有效地排序数据。

在本文中,我们讨论了如何使用 Pandas 库创建 CSV 文件。 此外,我们还讨论了两种常见的数据拆分技术,行式数据拆分和列式数据拆分。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便