Python:在列表中存储多个数据帧

Dr.*_*ill 6 python store list dataframe pandas

我有一个循环读取文档中的 Excel 工作表。我想将它们全部存储在一个列表中:

  DF_list= list()

  for sheet in sheets:
     df= pd.read_excel(...)
     DF_list = DF_list.append(df)
Run Code Online (Sandbox Code Playgroud)

如果我输入:

[df df df df]
Run Code Online (Sandbox Code Playgroud)

有用。

抱歉,我有 Matlab 背景,不太习惯 Python,但我喜欢它。谢谢。

Mik*_*ler 13

.append()修改列表并返回None. 您在第一个循环中覆盖DF_listwithNone并且追加将在第二个循环中失败。

所以:

DF_list = list()

for sheet in sheets:
    DF_list.append(pd.read_excel(...))
Run Code Online (Sandbox Code Playgroud)

或者使用列表理解:

DF_list = [pd.read_excel(...) for sheet in sheets] 
Run Code Online (Sandbox Code Playgroud)

  • 公平地说,他还解释了为什么代码不起作用。这对初学者来说非常有用。 (5认同)

Sup*_*tew 8

尝试这个

DF_list= list()

for sheet in sheets:

   df = pd.read_excel(...)

   DF_list.append(df)
Run Code Online (Sandbox Code Playgroud)

或者对于更紧凑的python,这样的事情可能会做

DF_list=[pd.read_excel(...) for sheet in sheets]
Run Code Online (Sandbox Code Playgroud)


Max*_*axU 4

如果您将使用参数sheet_name=None

dfs = pd.read_excel(..., sheet_name=None)
Run Code Online (Sandbox Code Playgroud)

它将返回数据帧的字典:

sheet_name : string, int, mixed list of strings/ints, or None, default 0

    Strings are used for sheet names, Integers are used in zero-indexed
    sheet positions.

    Lists of strings/integers are used to request multiple sheets.

    Specify None to get all sheets.

    str|int -> DataFrame is returned.
    list|None -> Dict of DataFrames is returned, with keys representing
    sheets.

    Available Cases

    * Defaults to 0 -> 1st sheet as a DataFrame
    * 1 -> 2nd sheet as a DataFrame
    * "Sheet1" -> 1st sheet as a DataFrame
    * [0,1,"Sheet5"] -> 1st, 2nd & 5th sheet as a dictionary of DataFrames
    * None -> All sheets as a dictionary of DataFrames
Run Code Online (Sandbox Code Playgroud)