我所有的文件都有下面的标题,它们可以追溯到几年前。我希望能够读取每个文件,然后将文件名中的日期作为列添加。
文件类型截至2015-04-01.csv
path = 'C:\\Users\\'
filelist = os.listdir(path) #All of my .csv files I am working with
file_count = len(filelist) #I thought I could do a for loop and use this as a the range
df = Series(filelist) #I just added this because I couldn't get the date from a list
date_name = df.str[15:-4] #This gives me the date
我试过的是:
for file in filelist:
df = pd.read_csv(file)
现在,我想从文件名中提取date_name,并添加一个名为date的列。每个文件都是完全相同的,但是我想跟踪随着时间的变化,唯一的日期是在文件的名称上找到的。
那我就把它加上去。
path = 'C:\\Users\\'
filelist = glob.glob(path + "/*.csv")
frame = pd.DataFrame()
list = []
for file in filelist:
df = pd.read_csv(file)
list_.append(df)
frame = pd.concat(list)
如何将date_name添加到文件/dataframe? 1)读取文件;2)根据文件名添加日期列;3)读取下一个文件;4)添加日期列;5)追加;6)对路径中的所有文件重复
编辑--我想我有工作要做--这是最好的方法吗?有人能解释一下列表= []在做什么吗?
path = 'C:\\Users\\'
filelist = os.listdir(path)
list = []
frame = pd.DataFrame()
for file in filelist:
df2 = pd.read_csv(path+file)
date_name = file[15:-4]
df2['Date'] = date_name
list.append(df2)
frame = pd.concat(list)
发布于 2015-05-22 17:36:17
这似乎是一种合理的方法。pd.concat
记录了一张熊猫物品的列表,并将它们连在一起。append
在遍历文件时将每个frame
添加到列表中。不过,我认为有两件事需要改变。
frame = pd.DataFrame()
。它没有做任何事情,因为您正在将dataframes
追加到列表中。list
的名称更改为其他内容。也许是frames
,因为它是对内容的描述,并不意味着什么。https://stackoverflow.com/questions/30405420
复制相似问题