如何将多个数据帧缩减为一个

问题描述 投票:0回答:1

我的目录中有许多文件夹,每个文件夹都有(

images folder & labels text
),我想通过将文件夹名称与图像名称连接起来使它们成为唯一的名称,将它们组合到一个数据帧文件中。 我目录的结构如下:

$ tree
.
├── sample
│   ├---- folder_1 ----|-- -- train.jsonl
|   |                  |----- imgs 
|   |                  |          └───├── 0.png
|   |                  |              └── 1.png
|   |                  |              └── 2.png
|   |                  |              └── 3.png
..  ..                ...               ...
|   |                  |              └── n.png
│   ├---- folder_2 ----|-- -- train.jsonl
|   |                  |----- imgs 
|   |                  |          └───├── 0.png
|   |                  |              └── 1.png
|   |                  |              └── 2.png
|   |                  |              └── 3.png
..  ..                ...               ...
|   |                  |              └── n.png
│   ├---- folder_3 ----|-- -- train.jsonl
|   |                  |----- imgs 
|   |                  |          └───├── 0.png
|   |                  |              └── 1.png
|   |                  |              └── 2.png
|   |                  |              └── 3.png
..  ..                ...               ...
|   |                  |              └── n.png

在每个文件夹中,

train.jsonl
文件包含图像名称和相应的文本例如
folder_1

{"file_name": "0.png", "text": "Hello"}
{"file_name": "1.png", "text": "there"}

在其他方面也是如此

folder_2
:

{"file_name": "0.png", "text": "Hi"}
{"file_name": "1.png", "text": "there from the second dir"}

....

我想通过用 pandas 或 python 读取那些 json 行并将父目录与图像名称连接来更新

file_name
路径:

import pandas as pd
import os 
df1 = pd.read_json(path_or_buf = 'sample/folder_1/train.jsonl',lines=True,)
df2 = pd.read_json(path_or_buf = sample/folder_2/train.jsonl,lines=True,)
df3 = pd.read_json(path_or_buf = sample/folder_3/train.jsonl,lines=True,)
df4 = pd.read_json(path_or_buf = sample/folder_4/train.jsonl,lines=True,)
df = df1+df2+df3+df4 + ....

所以预期的 df 应该是这样的:

       file_name                    text
0  sample/folder_1/0.png           Hello
1  sample/folder_1/1.png           there
2  sample/folder_2/0.png            Hi
3  sample/folder_2/1.png         there from the second dir
  ..........                          ........

为了使它们独一无二,我们可以循环遍历一个数据框文件,将它们组合在一起

python json pandas deep-learning operating-system
1个回答
0
投票
import pandas as pd
import os

df = pd.DataFrame(columns=['file_name', 'text'])

# Traverse the directory recursively
for root, dirs, files in os.walk('sample'):
    for file in files:
        if file == 'train.jsonl':
            df_temp = pd.read_json(os.path.join(root, file), lines=True)
            df_temp['file_name'] = os.path.join(root, 'imgs', df_temp['file_name'])

            df = df.append(df_temp, ignore_index=True)

print(df)
© www.soinside.com 2019 - 2024. All rights reserved.