我有一个很长的时间序列,每年都存档在与今年相对应的文件夹中。但是,在每个文件夹中,数据并不是记录在单个文件中,而是记录在每月的文件中。
例如1954 > 四月、八月、十二月...九月
当我使用 Glob 导入这些文件并使用 Pandas 创建 Dataframe 时,它们会按照相同的顺序导入(见上图)。但是,相反,我需要一个正确的月份序列(一月、二月、三月……)来绘制和使用它们。所以,我的问题是:
有什么方法可以强制 Glob 按特定顺序导入文件,或者使用 Pandas 重新排列文件?
path = r'path'
allFiles = glob.glob(path+"/*.dtf")
df = pd.DataFrame()
list_ = []
for file_ in allFiles:
df = pd.read_csv(file_,header = None,sep=r"\s*")
list_.append(df)
df = pd.concat(list_)
谢谢。
最佳答案
您可以使用concat
带有参数 keys
和文件名:
测试数据为here .
path = r'path-dtfs'
#add /* for read subfolders
allFiles = glob.glob(path+"/*/*.dtf")
print (allFiles)
['path\\1954\\FEB.dtf', 'path\\1954\\JAN.dtf', 'path\\1955\\APR.dtf', 'path\\1955\\MAR.dtf']
list_ = []
for file_ in allFiles:
df = pd.read_csv(file_,header = None,sep=r"\s+")
list_.append(df)
然后通过 split
创建新列和 insert
。为了正确排序需要ordered categorical 与 sort_values
:
df = pd.concat(list_, keys=allFiles)
.reset_index(level=1, drop=True)
.rename_axis('years').reset_index()
s = df['years'].str.split('\\')
df['years'] = s.str[-2].astype(int)
df.insert(1, 'months', s.str[-1].str.replace('.dtf', ''))
#add all missing months
cats = ['JAN','FEB','MAR','APR']
df['months'] = df['months'].astype('category', categories=cats, ordered=True)
df = df.sort_values(['years','months']).reset_index(drop=True)
print (df)
years months 0 1 2
0 1954 JAN 0 1 2
1 1954 JAN 1 5 8
2 1954 FEB 0 9 6
3 1954 FEB 1 6 4
4 1955 MAR 5 6 8
5 1955 MAR 4 7 9
6 1955 APR 0 3 6
7 1955 APR 1 4 1
另一个解决方案是通过 str.extract
创建 datetime
列与 to_datetime
:
df = pd.concat(list_, keys=allFiles)
.reset_index(level=1, drop=True)
.rename_axis('dates')
.reset_index()
df['dates'] = df['dates'].str.extract('path\\\(.*).dtf', expand=False)
df['dates'] = pd.to_datetime(df['dates'], format='%Y\%b')
df = df.sort_values('dates').reset_index(drop=True)
print (df)
dates 0 1 2
0 1954-01-01 0 1 2
1 1954-01-01 1 5 8
2 1954-02-01 0 9 6
3 1954-02-01 1 6 4
4 1955-03-01 5 6 8
5 1955-03-01 4 7 9
6 1955-04-01 0 3 6
7 1955-04-01 1 4 1
类似的解决方案是使用 to_period
的月份
:
df = pd.concat(list_, keys=allFiles)
.reset_index(level=1, drop=True)
.rename_axis('periods').reset_index()
df['periods'] = df['periods'].str.extract('path\\\(.*).dtf', expand=False)
df['periods'] = pd.to_datetime(df['periods'], format='%Y\%b').dt.to_period('M')
df = df.sort_values('periods').reset_index(drop=True)
print (df)
periods 0 1 2
0 1954-01 0 1 2
1 1954-01 1 5 8
2 1954-02 0 9 6
3 1954-02 1 6 4
4 1955-03 5 6 8
5 1955-03 4 7 9
6 1955-04 0 3 6
7 1955-04 1 4 1
关于python - 使用 glob 按特定顺序导入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45250496/