用python从多个文件中提取数据

2024-04-26 11:45:55 发布

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

我试图从一个包含12.txt文件的目录中提取数据。每个文件包含我要提取的3列数据(X,Y,Z)。我想在一个df(InforDF)中收集所有数据,但到目前为止,我只成功地创建了一个包含所有X、Y和Z数据的df。这是我的代码:

import pandas as pd
import numpy as np
import os
import fnmatch

path = os.getcwd()

file_list = os.listdir(path)

InfoDF = pd.DataFrame()

for file in file_list:
    try:
        if fnmatch.fnmatch(file, '*.txt'):
            filedata = open(file, 'r')
            df = pd.read_table(filedata, delim_whitespace=True, names={'X','Y','Z'})

    except Exception as e:
        print(e)

我做错什么了?在


Tags: 文件数据pathimport目录txtdfos
3条回答

我想您需要^{}来选择所有文件,在list comprehension中创建DataFramesdfs的列表,然后使用^{}

files = glob.glob('*.txt')
dfs = [pd.read_csv(fp, delim_whitespace=True, names=['X','Y','Z']) for fp in files]

df = pd.concat(dfs, ignore_index=True)
  • 正如camilleri在上面提到的,您正在重写循环中的df
  • 同样,抓住一个普遍的异常也没有意义

解决方案:在循环之前创建一个空的数据帧InfoDF,然后使用append或{a2}来填充更小的df

import pandas as pd
import numpy as np
import os
import fnmatch

path = os.getcwd()

file_list = os.listdir(path)

InfoDF = pd.DataFrame(columns={'X','Y','Z'}) # create empty dataframe
for file in file_list:
    if fnmatch.fnmatch(file, '*.txt'): 
        filedata = open(file, 'r')
        df = pd.read_table(filedata, delim_whitespace=True, names={'X','Y','Z'})
        InfoDF.append(df, ignore_index=True)
print InfoDF
df = pd.read_table(filedata, delim_whitespace=True, names={'X','Y','Z'})

这一行在循环的每次迭代中替换df,这就是为什么在程序的末尾只有最后一个。在

您可以做的是将所有的数据帧保存在一个列表中,并在末尾连接它们

^{pr2}$

或者,您可以编写它:

df_list = pd.concat([pd.read_table(open(file, 'r'), delim_whitespace=True, names={'X','Y','Z'})  for file in file_list if fnmatch.fnmatch(file, '*.txt')])

相关问题 更多 >