python - 使用 glob 按特定顺序导入文件

标签 python pandas dataframe glob

我有一个很长的时间序列,每年都存档在与今年相对应的文件夹中。但是,在每个文件夹中,数据并不是记录在单个文件中,而是记录在每月的文件中。

例如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/

相关文章:

python - 计算日期范围内 Python Pandas 数据框的最大值

python - Pandas 将分钟数字索引(0 到 1440)转换为日期时间

python - 按组和虚拟代码分类变量转换长格式分类数据

python - 如何正确合并鸭子类型(duck typing)以返回原始类型?

python - 如何通过多处理在单独的 Python 进程中使用用 Cython 包装的外部 C 库?

python - 对数据框中的 bool 值求和

python - Dataframe 无法填充 Pandas 中的 NaN 值

python - SQL语法错误:1064,如何修复?

python - 在 pd.DataFrame 中插入一行而不加载文件

python - 如何在 Pandas 数据框中堆叠行以获得一个 "long row"?