根据列中具有相同值的 CSV 文件在 python 中创建新的 CSV 文件

Create new CSV files in python from the CSV files having same values in the column

我正在编写一个 python 脚本来从一个文件夹中读取多个 csv 文件。我需要根据一列(第 3 列)中存在的值合并 csv 文件,并从中创建新的 csv 文件。

例如:我有 3 个 csv 文件,如下所示:

csv 1: csv 2: csv 3:

2 4 1994 4 4 1995 2 4 1997
2 4 1994 0 4 1995 2 4 1997
9 0 1994 9 6 1995 9 0 1998
6 7 1994 6 9 1996 6 7 1998
6 4 1995 4 2 1996 6 4 1998
6 3 1995 4 1 1997 6 3 1998
6 5 1995 0 5 1997 6 5 1999
8 7 1995 7 8 1997 8 7 1999

输出应如下所示:

O/P 1: O/P 2: O/P 5:

2 4 1994 6 4 1995 9 0 1998
2 4 1994 6 3 1995 6 7 1998
9 0 1994 6 5 1995 6 4 1998
6 7 1994 8 7 1995 6 3 1998
4 4 1995
0 4 1995
9 6 1995

O/P 3: O/P 4: O/P 6:

6 9 1996 4 1 1997 6 5 1999
4 2 1996 0 5 1997 8 7 1999
7 8 1997

如果有人能帮助我,我将不胜感激!任何建议都会很有帮助。

谢谢。

我使用 glob 自动搜索 .csv 文件,但如果它们已经在某个变量中初始化,您可以合并它们并仅使用 for year in all_csv['YEAR'].unique()...

的一部分
import pandas as pd
import glob

path = "/home/gustavo/" # path your csv files are (in my example is store in /home/gustavo)

all_csv = pd.DataFrame()
for file in glob.glob(path + "*.csv") : # *.csv search for all csv files in path
    all_csv = all_csv.append(pd.read_csv(file, header = None), ignore_index = True)

all_csv = all_csv.rename(columns = {0 : 'A', 1 : 'B', 2 : 'YEAR'})

# Filter for each year value and transform to csv 
for year in all_csv['YEAR'].unique() :
    all_csv[all_csv['YEAR'] == year].to_csv(f'{year}.csv', index=False)

输出: