TypeError: Type Tuple cannot be instantiated; use tuple() instead

TypeError: Type Tuple cannot be instantiated; use tuple() instead

我用以下代码编写了一个程序:

import pandas as pd
import numpy as np
from typing import Tuple

def split_data(self, df: pd.DataFrame, split_quantile: float) -> Tuple(pd.DataFrame, pd.DataFrame):
    '''Split data sets into two parts - train and test data sets.'''
    df = df.sort_values(by='datein').reset_index(drop=True)
    quantile = int(np.quantile(df.index, split_quantile))
    return (
        df[df.index <= quantile].reset_index(drop=True),
        df[df.index > quantile].reset_index(drop=True)
    )

程序returns出现以下错误:TypeError: Type Tuple cannot be instantiated; use tuple() instead。我明白,我可以通过用 tuple() 替换 Tuple(pd.DataFrame, pd.DataFrame) 来解决我的代码,但是我丢失了信息的一部分,我的元组将包含两个 pandas 数据帧。

请问能不能帮帮我,如何解决错误同时不丢失信息?

使用方括号:

Tuple[pd.DataFrame, pd.DataFrame]

来自docs

Tuple type; Tuple[X, Y] is the type of a tuple of two items with the first item of type X and the second of type Y. The type of the empty tuple can be written as Tuple[()].

编辑:With the release of python 3.9, you can now do this with the builtins.tuple 输入而不是必须导入 typing。例如:

>>> tuple[pd.DataFrame, pd.DataFrame]
tuple[pandas.core.frame.DataFrame, pandas.core.frame.DataFrame]

你还是要用方括号。