程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

七爪源码:在 Python 中创建数据集的自动化(使用 Pandas)

hfteth 2025-05-26 15:59:29 技术文章 4 ℃

在日常操作中,数据专业人员会遇到检索、清理和合并数据的不同方式。 在这篇文章中,我们将了解如何从文件夹中的 JSON 文件自动化和创建数据集。

JSON 文件:这是一个常见的用例,其中一个文件夹可能包含具有相似结构的 json 文件,我们将它们组合起来得到一个数据集。 因此,假设文件具有相同的结构。

文件夹:我们创建一个包含几个 json 文件和文本文件的测试文件夹。 这用作源文件夹。

JSON 中的数据:Json 的结构类似。 这是文件 1

[{"customer":"John",
"age":"25",
"sex":"male",
"amount":"32000"},
{"customer":"Ron",
"age":"20",
"sex":"male",
"amount":"12000"}]

这是文件 2

[{"customer":"Daisy",
"age":"22",
"sex":"female",
"amount":"20000"},
{"customer":"Anna",
"age":"26",
"sex":"female",
"amount":"24000"}]


算法:

  1. 我们的文件夹由异构文件(Json 和文本文件)组成。 使用 os 函数 listdir() 将所有文件名添加到列表中。
  2. 为 Json 文件创建一个列表,然后遍历文件名列表并将每个带有“.json”的名称添加到列表中。
  3. 启动数据框变量。
  4. 创建一个数据框列表以添加从 json 文件创建的各个数据框。
  5. 循环遍历 json 列表并将 json 文件读取到数据帧。 将数据框添加到数据框列表中。
  6. 将所有数据帧添加到最终数据帧
  7. 打印以检查数据框的形状
  8. 通过创建数据集,将最终数据帧以 csv 格式写入指定文件夹。

代码:

#os library helps with operating system dependent functionality
import os
# pandas library for creating data frames
import pandas as pd

# give the file path of the folder
file_path=r'folderpath\Test_Folder'

# get the list of files in the folder
List_of_files=os.listdir(file_path)
print(List_of_files)# a list to collect the json files
json_list = []
df=pd.DataFrame()

# looping through the files
for i in List_of_files:
    if i.endswith('.json'):
        json_list.append(i)
    else:
        pass

print(json_list)# create a list
dataframes=list()# creating data frames
for item in json_list:
    path=(os.path.join(file_path,item))
    dataframes.append(pd.read_json(path))
# final data frame
final_df=pd.concat(dataframes,ignore_index=True)# final df shape
print(final_df.shape)
print(final_df)  final_df.to_csv('destination_path/name_of_the_file.csv')

代码输出:

['1.json', '2.json', 'test1.txt', 'test2.txt']['1.json', '2.json'](4, 4)  customer  age     sex  amount
0     John   25    male   32000
1      Ron   20    male   12000
2    Daisy   22  female   20000
3     Anna   26  female   24000

我们只是自动化了读取文件和合并它们的过程。 因此,我们可以自动化创建数据集的流程。 这为公司增加了很多价值并节省了时间,尤其是在为数据分析设计数据集时。 我希望本指南可以帮助您创建和合并数据集。

谢谢你。


关注七爪网,获取更多APP/小程序/网站源码资源!

最近发表
标签列表