Pandas 获取加载到内存中的所有数据帧的列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41113663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:36:51  来源:igfitidea点击:

Pandas Get a List Of All Data Frames loaded into memory

pythonpandas

提问by Kartik

I am using pandas to read several csv files into memory for processing and at some point would like to list all the data frames I have loaded into memory. Is there a simple way to do that? (I am thinking something like %ls but only for the data frames that I have available in memory)

我正在使用 Pandas 将几个 csv 文件读入内存进行处理,并且在某些时候想列出我加载到内存中的所有数据帧。有没有一种简单的方法可以做到这一点?(我正在考虑类似 %ls 的事情,但仅适用于我在内存中可用的数据帧)

回答by datawrestler

You could list all dataframes with the following:

您可以使用以下内容列出所有数据框:

import pandas as pd

# create dummy dataframes
df1 = pd.DataFrame({'Col1' : list(range(100))})
df2 = pd.DataFrame({'Col1' : list(range(100))})

# check whether all variables in scope are pandas dataframe. 
# Dir() will return a list of string representations of the variables. 
# Simply evaluate and test whether they are pandas dataframes
alldfs = [var for var in dir() if isinstance(eval(var), pd.core.frame.DataFrame)]

print(alldfs) # df1, df2

回答by Alex

I personally think thisapproach is much better (if in ipython).

我个人认为这种方法要好得多(如果在 ipython 中)。

import pandas as pd
%whos DataFrame

回答by Jorge Martins

building on previous answers ... this returns a list

以以前的答案为基础……这将返回一个列表

import pandas as pd 
%who_ls DataFrame 

however, if you try to run a script it doesn't work

但是,如果您尝试运行脚本,则它不起作用

thus

因此

import pandas as pd
sheets=[]    
for var in dir():
    if isinstance(locals()[var], pd.core.frame.DataFrame)  and var[0]!='_':
        sheets.append(var)

since some DataFrames will have a copy for internal use only and those start with '_'

因为一些 DataFrames 将有一个仅供内部使用的副本,并且那些以“_”开头