如何在Python中对文件夹中的多个文件进行分组?

2024-09-29 23:26:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含30个CSV的文件夹。除了一个“UNITID”列之外,它们都有彼此唯一的列。我希望在所有CSV的UNITID列上执行groupby函数

最终,我想要一个数据帧,每个UNITID的所有列彼此相邻

我该怎么做呢

提前谢谢


Tags: csv数据函数文件夹groupbyunitid
2条回答

也许您可以将数据帧合并在一起,一次一个?大概是这样的:

# get a list of your csv paths somehow
list_of_csvs = get_filenames_of_csvs()

# load the first csv file into a DF to start with
big_df = pd.read_csv(list_of_csvs[0])

# merge to other csvs into the first, one at a time
for csv in list_of_csvs[1:]:
    df = pd.read_csv(csv)
    big_df = big_df.merge(df, how="outer", on="UNITID")

所有CSV将基于UNITID合并在一起,保留所有列的并集

dustin解决方案的另一个替代方案是functool的reduce函数和DataFrame.merge()的组合

这样,

from functools import reduce # standard library, no need to pip it
from pandas import DataFrame
# make some dfs

df1
   id col_one col_two
0   0       a       d
1   1       b       e
2   2       c       f
df2
   id col_three col_four
0   0         A        D
1   1         B        E
2   2         C        F
df3
   id  col_five  col_six
0   0         1        4
1   1         2        5
2   2         3        6

一行:

reduce(lambda x,y: x.merge(y, on= "id"), [df1, df2, df3])

   id col_one col_two col_three col_four  col_five  col_six
0   0       a       d         A        D         1        4
1   1       b       e         B        E         2        5
2   2       c       f         C        F         3        6

functools.reduce docs

pandas.DataFrame.merge docs

相关问题 更多 >

    热门问题