将导入文件的文件名添加到数据框

时间:2018-10-18 22:15:45

标签: python pandas

对于Python还是很新的,所以请耐心等待。我有一个文件目录,所有文件都具有类似的命名方案。文件名看起来像这样:

yob2004.txt yob2005.txt

我想做的是打开这些文件中的每个文件并添加到数据框。然后,我想从文件名中提取年份,并将其作为新列添加到数据框中。

我可以得到其中的一部分,但不能得到全部。

这是文件名中年份的年份提取代码。

filenames = glob.glob('names/*.txt')

#split off the beginning of of he file path plus 'yob' and only keep 
everything after that. ex. 1180.txt
split1 = [i.split('\yob', 1)[1] for i in filenames]

#split of the .txt from the strings in the list above
split2 = [i.split('.', 1)[0] for i in split1]

这是将所有文件连接在一起的代码

read_files = glob.glob("names/*.txt")

with open("allnames.txt", "wb") as outfile:
    for f in read_files:
        with open(f, "rb") as infile:
            outfile.write(infile.read())

我在想,我实际上需要做的是将第一个文件读入数据框中,然后从文件名中提取年份并将其写入数据框中的新列。然后移至下一个文件。冲洗。重复。

任何指导如何做到这一点?

1 个答案:

答案 0 :(得分:1)

这应该对您的数据有效,假设我有2个文件yob2004.txt和yob2005.txt:

#yob2004
1,2,3,4
2,3,4,5
5,6,7,8

#yob2005
8,9,10,11
a,b,c,d
f,j,k
i,j,k,l

我们看到这些文件具有不同的数据类型,并且行/列的数量不同,因此将涵盖大多数边缘情况:

import pandas as pd
from os import walk

f = []
for (dirpath, dirnames, filenames) in walk('/home/dkennetz/yobDf'):
    for x in filenames:
        if x.startswith('yob'):
            f.append(x)
#f = ['yob2005.txt', 'yob2004.txt'] created a list from filenames in directory ^^^

data = pd.DataFrame() # initialize empty df
for filename in f:
    df = pd.read_csv(filename, names=['col1', 'col2', 'col3', 'col4']) # read in each csv to df
    df['filename'] = filename # add a column with the filename
    data = data.append(df) # add all small df's to big df 

data['filename'] = data['filename'].map(lambda x: x.lstrip('yob').rstrip('.txt')) # get rid of yob and .txt and just keep year
print(data)

输出:

  col1 col2 col3 col4 filename
0    8    9   10   11     2005
1    a    b    c    d     2005
2    f    j    k  NaN     2005
3    i    j    k    l     2005
0    1    2    3    4     2004
1    2    3    4    5     2004
2    5    6    7    8     2004

输出将通过将年份放置在dfs不同大小的列和NAN旁边来告诉它来自哪个文件。