【问题标题】:Appending the results of for loop with if statement to Pandas Dataframe in Python将带有 if 语句的 for 循环的结果附加到 Python 中的 Pandas Dataframe
【发布时间】:2018-07-15 23:15:37
【问题描述】:

我正在用 Python 编写一个脚本,用于在选定文件夹中的一堆 .txt 文件中搜索选定的术语(单词/单词、句子),并打印出包含选定项的 .txt 文件的名称学期。目前使用 os 模块工作得很好:

import os

dirname = '/Users/User/Documents/test/reports'

search_terms = ['Pressure']
search_terms = [x.lower() for x in search_terms]

for f in os.listdir(dirname):
    with open(os.path.join(dirname,f), "r", encoding="latin-1") as infile:
        text =  infile.read()

    if all(term in text for term in search_terms):
        print (f)

输出将是这样的:

3003.txt
3002.txt
3006.txt
3008.txt

我想将这些结果作为字符串列附加到 Pandas Dataframe 中,但是当我尝试这样做时,我收到了错误消息:

lst = []

    if all(term in text for term in search_terms):
        lst.append(f)
        df = pd.DataFrame(lst)
        print (f)

如何做到这一点?

【问题讨论】:

  • ...什么错误信息?
  • 数据框调用不正确

标签: python pandas file directory python-os


【解决方案1】:

code 下面的新行由“*”表示。

问题代码

import os
import pandas as pd # new line * * *
import numpy as np # new line * * *

dirname = '/Users/User/Documents/test/reports'

search_terms = ['Pressure']
search_terms = [x.lower() for x in search_terms]

# Create empty dataframe to store file names # new line * * *
df = pd.DataFrame()  # new line * * *

for f in os.listdir(dirname):
    with open(os.path.join(dirname,f), "r", encoding="latin-1") as infile:
        text =  infile.read()

    if all(term in text for term in search_terms):
        print (f)
        # Store value 'f' inside a dataframe column
        df = df.append(pd.DataFrame({'file_names': ['new_file.txt']}), ignore_index=True)

示例代码

f = ['3003.txt', '3002.txt', '3006.txt', '3008.txt']
df = pd.DataFrame({'file_names': f})
df = df.append(pd.DataFrame({'file_names': ['new_file.txt']}), ignore_index=True)
df

【讨论】:

  • 谢谢,但有助于像列表一样使用 f 以避免标量值:df = df.append(pd.DataFrame({'files':[f]}),ignore_index=True)
猜你喜欢
  • 1970-01-01
  • 2017-08-06
  • 1970-01-01
  • 1970-01-01
  • 2021-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多