【问题标题】:python iterating on multiple filespython迭代多个文件
【发布时间】:2020-10-21 23:44:10
【问题描述】:

我有

file_2000.dta、file_2001.dta、file_2002.dta 等等。

我也有

file1_2000.dta、file1_2001.dta、file1_2002.dta 等等。

我想迭代文件年份。

Let (year) = 2000, 2001, 2002, etc

import file_(year) using pandas. 
import file1_(year) using pandas. 

file_(year)['name'] = file_(year).index
file1_(year)['name'] = file1_(year).index2

merged = pd.merge(file_(year), file1_(year), on='name') 

write/export merged_(year).dta

【问题讨论】:

  • 我不太清楚你想要实现什么
  • 我已经编辑添加了一些简化的代码

标签: python-3.x pandas loops


【解决方案1】:

在我看来,您需要使用read_stata function,根据您的 .dta 扩展名,循环读取文件,创建单独数据帧的列表以便能够单独使用它们,然后concatenate 将所有数据帧合二为一。

类似:

list_of_files = ['file_2000.dta', 'file_2001.dta', 'file_2002.dta']  # full paths here...

frames = []

for f in list_of_files:
    df = pd.read_stata(f)
    frames.append(df)

consolidated_df = pd.concat(frames, axis=0, ignore_index=True)

这些问题可能与您的情况有关:

How to Read multiple files in Python for Pandas separate dataframes

Pandas read_stata() with large .dta files

【讨论】:

    【解决方案2】:

    据我所知,Python 中没有“Let”关键字。要遍历目录中的多个文件,您可以简单地使用带有 os 模块的 for 循环,如下所示:

    import os
    
    directory = r'C:\Users\admin'
    for filename in os.listdir(directory):
        if filename.startswith("file_200") and filename.endswith(".dat"):
            # do something
        else:
            continue
    

    另一种方法是使用正则表达式告诉 python 在迭代期间要匹配的文件名。模式应该是:pattern = r"file_20\d+"

    【讨论】:

      猜你喜欢
      • 2011-05-25
      • 1970-01-01
      • 1970-01-01
      • 2022-08-02
      • 1970-01-01
      • 1970-01-01
      • 2020-10-16
      • 2021-02-05
      • 1970-01-01
      相关资源
      最近更新 更多