比较从s3读取的每个文件的数据帧

2024-04-26 09:53:58 发布

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

我在awss3文件夹中有大量文件。我想在python中读取每个文件夹中的文件,并比较和合并dataframe,这样,如果另一个dataframe中的特定列值相似,则将相应的列值添加到list中,并将所有其他列值添加到下一行

例如:数据帧df1

A               B
books          [book1, book2, book3]
animal         [animal1, animal2, animal3]
place          [place1 , place2, place3]

dataframe df2

A .          B
name        [name1, name2, name3]
animal      [animal 5, animal 6]

那么结果应该是:df

A             B
books          [book1, book2, book3]
animal         [animal1, animal2, animal3, animal5, animal6]
place          [place1 , place2, place3]
name        [name1, name2, name3]

Tags: 文件夹dataframeplacebooksanimal列值book1book2
1条回答
网友
1楼 · 发布于 2024-04-26 09:53:58

通过^{}将所有数据帧连接起来,B的聚合值与列表理解中lambda函数中列表的扁平列表:

df = pd.concat([df1, df2], ignore_index=True)

f = lambda x: [z for y in x for z in y]
df3 = df.groupby('A', sort=False)['B'].apply(f).reset_index()
print (df3)
        A                                                B
0   books                            [book1, book2, book3]
1  animal  [animal1, animal2, animal3, animal 5, animal 6]
2   place                         [place1, place2, place3]
3    name                            [name1, name2, name3]

或:

#slow solution in large data
df = df.groupby('A', sort=False)['B'].sum().reset_index()

相关问题 更多 >