python-3.x - 如何读取多个文件然后连接:我具有检查文件是否存在并读取是否存在的功能,连接时面临问题
问题描述
5 个不同的文件夹中有 5 个文件,我编写了一个函数来检查文件是否存在并读取文件并存储在数据框中。我有连接函数说 pd.concat(file1,file2,file3,file,4,file5)。问题:不是每次我们都得到所有 5 个文件,很少我只得到 4 个文件,函数会读取文件,但问题在于连接。例如:文件 2 不存在,它给我错误文件 2 未定义。
代码 :
for x in f:
if x.startswith("File_A1"):
mypath = os.path.join(root,'A1','ABB','BGH',x)
A1 = pd.read_csv(mypath, delimiter="|",header = 1)
A1['GROUP']= 'A1'
A1.loc[A1['coms'] == "ASIA"]
A1.drop_duplicates(inplace = True)
elif x.startswith("File_A2"):
mypath = os.path.join(root,'A2','ABB','BGH',x)
A2 = pd.read_csv(mypath,delimiter="|",header = 1)
A2['GROUP']= 'A2'
A2.loc[A2['coms'] == "ASIA"]
A2.drop_duplicates(inplace = True)
elif x.startswith("File_A3"):
mypath = os.path.join(root,'A3','ABB','BGH',x)
A3 = pd.read_csv(mypath,delimiter="|",header = 1)
A3['GROUP']= 'A3'
A3.loc[A3['coms'] == "ASIA"]
A3.drop_duplicates(inplace = True)
df = pd.concat([A1,A2,A3])
解决方案
我认为最好的方法是通过以下方式创建 DataFrames 列表append
:
编辑:您可以按文件名的开头列表循环,并A1
通过以下A2
方式动态创建start.split('_')[1]
:
dfs = []
for x in f:
starts = ["File_A1", "File_A2", "File_A3"]
for start in starts:
if x.startswith(start):
mypath = os.path.join(root,start.split('_')[1],'ABB','BGH',x)
df = pd.read_csv(mypath, delimiter="|",header = 1)
df['GROUP']= start.split('_')[1]
df.loc[df['coms'] == "ASIA"]
df.drop_duplicates(inplace = True)
dfs.append(df)
df = pd.concat(dfs, ignore_index=True)
推荐阅读
- java - 电话身份验证验证无法验证并引发此错误
- javascript - 触摸事件侦听器在 iframe 中不起作用
- c# - 是否有定义 HTML 解码语言的特定方法?
- linux - 如何为Android构建【openSSL-1.0.2u】,如果可能,如何合并Android Makefile?
- apache-spark - 如何在 spark scala 中更快地处理 .gz 文件?
- slack - Slack 传入 webhook 中的确认按钮
- ios - 如何在 iOS SWIFT 中显示来自 AWSS3 存储桶的完整图像?
- php - 谷歌日历 API 与 PHP 的问题
- node.js - 使用 fluent-ffmpeg 在 nodejs 上处理 ffmpeg 命令
- scala - 编译器会尽可能将实例方法的调用优化为静态方法吗?