python - 从存储在不同文件夹中的所有 csv 文件创建唯一的数据框
问题描述
我有几个文件夹,其中存储了几个 csv 文件。我想使用 Python 中的函数创建一个唯一的文件/数据框。
名为 的文件夹Main_Folder
有 3 个子文件夹:Folder from A
、Folder from B
、Folder from C
。文件夹A
包含三个 csv 文件:
- 文件名1+键;
- 文件名2+板;
- 文件名3+猫;
同样的其他两个文件夹,B
- 文件名1+味道;
- 文件名2+board_1;
- 文件名3+狗;
和C
- 文件名+测试;
- 文件名+b;
- 文件名+d;
我试过的是
def create_dataframe(nam):
path = "path/Folder from "+nam+"/"
files = [f.split('.')[0] for f in listdir(path) if isfile(join(path, f))]
dataframe={}
for file in files:
dataframe[file] = pd.read_csv(path+file+'.csv')
但它似乎不起作用(当我调用函数时没有输出)。我认为我的方法是错误的。我想要的输出将是一个数据框(唯一),其中包含来自不同三个文件夹(A、B 和 C)的所有文件,还有两个额外的列,一个用于 A/B 和 C(即可以告诉我数据集来自哪里from) 和另一个用于文件名。
像这样的东西:
Col1 Col2 Col3 Col4 .... Source FileName
.. .. .. .. .. .. .. A filename1+tast
.. .. .. .. .. .. .. .. ..
.. .. .. .. .. .. .. A filename3+cat
.. .. .. .. .. .. .. B filename1+tast
.. .. .. .. .. .. .. .. ..
.. .. .. .. .. .. .. B filename3+dog
.. .. .. .. .. .. .. C filename+test
.. .. .. .. .. .. .. .. ..
.. .. .. .. .. .. .. C filename+d
如果您需要更多详细信息或对此有任何疑问,请告诉我。
解决方案
您的函数不起作用,因为它不返回任何内容。
要组合不同的数据框,您可以使用pd.concat
方法。
例如:
def create_dataframe(paths):
""" Creates combined dataframe from csv files in paths """
def get_files_in_path(path):
return [f.split('.')[0] for f in listdir(path) if isfile(join(path, f))]
dataframes = {
(path, file): pd.read_csv(path + file + '.csv')
for path in paths
for file in get_files_in_path(path)
}
df = pd.concat(dataframes, names=['path', 'file', '_'])
return df
paths = [f"path/Folder from {name}/" for name in ['A', 'B', 'C']]
df = create_dataframe(paths)
您还可以调用df.reset_index(inplace=True)
将索引转换为列:
推荐阅读
- javascript - 使用 forEach 的任务未完成
- powershell - 使用 Powershell 脚本扫描在线设备上的服务
- reactjs - 如何使用选项卡导航器将道具传递给 Screen 组件?
- swiftui - SWIFTUI - 如何更改数组中随机变量的值?
- android - 一种方法从 WebServer 获得响应,而另一种方法需要该方法的答案才能返回某些东西,不幸的是我得到了 null
- c# - 获取对象mongodb驱动网络核心列表
- python - 从“第二行”中的json中抓取数据
- c++ - 简单的 C++ ofstream 项目在部署时不起作用
- react-native - 如何在 API 使用 redux 获取数据之前显示 Loader?
- python - 不确定 /?(.+) 在我的正则表达式中如何工作