【问题标题】:How can I loop through a directory, extract only .txt files, and put each .txt file into a separate but accessible DataFrame?如何遍历目录,仅提取 .txt 文件,并将每个 .txt 文件放入单独但可访问的 DataFrame 中?
【发布时间】:2017-08-15 02:33:31
【问题描述】:

我有一个 PDF 文件和大约 130 个 .txt 文件。

PDF 文件没用,需要跳过。每个 .txt 文件都包含名称数据,每个 .txt 文件代表从 1880 年到 2010 年的年份。

所有 .txt 文件的格式都相同:姓名、性别、在特定年份使用该姓名的人数。以下是其中一个 .txt 文件的示例:

Mary,M,8754
Susan,M,5478
Brandy,M,5214
etc...

每个 .txt 文件中可能有数千个名称。我的问题基本上是标题所问的。我想知道如何有效地获取每个 .txt 文件并将它们放入单独但可访问的 DataFrames 中。我希望能够快速搜索并提取特定名称的平均值或标准差等内容。

我已经研究了多个具有类似问题/疑虑的主题,但没有一个对我有任何实际用处:

Import multiple csv files into pandas and concatenate into one DataFrame Read multiple *.txt files into Pandas Dataframe with filename as column header

creating pandas data frame from multiple files

我们不胜感激。

【问题讨论】:

  • 文件没有标题?
  • @piRSquared 不,文件没有任何标题

标签: python pandas numpy dataframe


【解决方案1】:
import pandas as pd
from glob import glob

path = 'your_path' # use your path
files = glob(path + '/*.txt')

get_df = lambda f: pd.read_csv(f, header=None, names=['Name', 'Sex', 'Count'])

dodf = {f: get_df(f) for f in files}

【讨论】:

  • 啊,这是一个很好的解决方案。不过有几个问题......你的“dodf”代表“数据帧的数据”吗?另外,既然每个文件都在各自的 DataFrame 中,我该如何访问它们(假设我想打印第一个文件)?
  • @shadewolf 'dict of dataframes'
  • @shadewolf 你可以使用dodf[files[0])
  • 我在上面的示例中收到“列表索引超出范围”错误,这很奇怪,因为每个文件都已分配给数据框。我在这里错过了什么吗?
  • @shadewolf 您可能正在覆盖files 名称?这对我来说毫无意义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-25
  • 2021-01-04
  • 1970-01-01
  • 2019-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多