首页 > 解决方案 > 在不影响默认分隔符的情况下打印没有索引的熊猫数据框

问题描述

我正在运行一个 python 脚本,它通过在多个目录中的迭代生成多个变量。脚本完成后,我只想对匹配特定模式的少数对象(在本例中为数据帧)执行一些操作。

我可以检索要对其执行操作的变量列表,如下所示:

failed_runs_finder = re.compile(r'FAILEDRuns_') # I want to perform the operations on the dataframes which match this pattern.
list_dfs = list(filter(failed_runs_finder.findall, dir())) # this will get me the list with the names of the dataframes

这会给我类似的东西:

['FAILEDRuns_0112',
 'FAILEDRuns_0121',
 'FAILEDRuns_0126',
 'FAILEDRuns_0129',
 'FAILEDRuns_0131',
 'FAILEDRuns_0134',
 'FAILEDRuns_0135',
 'FAILEDRuns_0137',
 'FAILEDRuns_0142',
 'FAILEDRuns_0153',
 'FAILEDRuns_0165',
 'FAILEDRuns_0171',
 'FAILEDRuns_0175']

我现在想遍历此列表中的所有对象(它们是数据帧)(并使用该shape()方法执行一些简单的操作,例如获取每个对象中的行数)。这里的问题是这个列表中的元素是字符串,而我想通过它们在这个列表中的名称来访问对象本身。

例如,如果我这样做:

for i in list_dfs:
    print(getattr(i, 'shape'))

我得到:

AttributeError: 'str' object has no attribute 'shape'

标签: pythonpandasattributes

解决方案


您可以使用exec()函数来完成任务:

import pandas as pd
failed_runs_finder = re.compile(r'FAILEDRuns_') # I want to perform the operations on the dataframes which match this pattern.
list_dfs = list(filter(failed_runs_finder.findall, dir())) 
for i in list_dfs:
    exec("if isinstance({}, pd.DataFrame): print(getattr({}, 'shape'))".format(i, i))

exec()函数将评估字符串并执行它。执行代码的范围将与内联运行代码相同。因此,我们可以使用内联代码范围内可用的任何导入的模块、对象或函数等(在本例中为pd)。

警告:这可能不是一个好主意,而且效率极低。此外,像这样使用 exec() 存在一些安全风险。

我建议你寻找另一种方法。


推荐阅读