[英]Error in list comprehension with `locals()` in python
I have run a python script that created multiple variables. 我已经运行了创建多个变量的python脚本。 Now I want to iterate over a few dataframes (created by the script) matching a specific pattern and perform simple operations on them.
现在,我要遍历匹配特定模式的几个数据帧(由脚本创建),并对它们执行简单的操作。 Initially I want to get the number of rows (with
shape()
) of each of the dataframes in list_dfs
, as shown below: 最初,我想获取
list_dfs
中每个数据list_dfs
的行数(具有shape()
),如下所示:
['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']
In fact if I do: 实际上,如果我这样做:
for i in list(filter(failed_runs_finder.findall, dir())):
print(locals()[i].shape[0])
I get the number of rows printed onto the screen: 我得到打印到屏幕上的行数:
1
0
0
0
1
0
0
0
0
0
0
0
0
Which contains the information that I need, though not in the format that I want. 其中包含我需要的信息,尽管不是我想要的格式。 Eventually what I need to know is the number of 1's and the number of zero's, so I thought about getting a list comprehension, to eventually compare the total sum (ie the number of 1's) with the length of the list ie the total number of elements.
最终,我需要知道的是1的数量和零的数量,因此我考虑了对列表的理解,以最终将总和(即1的数量)与列表的长度(即...的总数)进行比较元素。
However, if I do: 但是,如果我这样做:
[locals()[i].shape[0] for i in list_dfs]
I get the following error: 我收到以下错误:
KeyError: 'FAILEDRuns_0112'
I don't quite understand where the error is coming from. 我不太了解错误的来源。 As far as I see, it is not in terms of syntax of list comprehensions.
据我所知,这不是列表理解的语法。
Does it have anything to do with using locals()
within a list comprehension? 它与在列表理解中使用
locals()
有什么关系吗?
My second option would be to build a df iteratively and get the sum, though I think it is simpler with list comprehension and I don't quite get where the error is coming from. 我的第二个选择是迭代地构建df并获取总和,尽管我认为列表理解更简单,而且我不太了解错误的出处。
Try this instead if you really must rely on locals()
: 如果确实必须依赖
locals()
请尝试以下方法:
[v.shape[0] for k, v in locals().items() if k in list_dfs]
However it would probably be a better approach, as suggested, to use a single dict
to store all the names and DataFrame
objects instead. 但是,如建议的那样,使用单个
dict
来存储所有名称和DataFrame
对象可能是更好的方法。
If you want to get the counts of rows: 如果要获取行数:
from collections import Counter
cnt = Counter(v.shape[0] for k, v in locals().items() if k in list_dfs)
cnt[1]
# 2
cnt[0]
# 11
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.