【问题标题】:Argument of type "Series[Dtype]" cannot be assigned to parameter of type "DataFrame"“Series[Dtype]”类型的参数不能分配给“DataFrame”类型的参数
【发布时间】:2020-11-26 01:07:28
【问题描述】:

我定义了以下辅助方法

def load_excel(file_path: str, sheet_name: str = ''):
    if sheet_name == '':
        df = pd.read_excel(file_path).fillna('').apply(lambda x: x.astype(str).str.lower())
    else:
        df = pd.read_excel(file_path, sheet_name).fillna('').apply(lambda x: x.astype(str).str.lower())
        
    return df

def build_score_dict(keywords_df: pd.DataFrame, tokens: list):
    """
    Returns a tuple of two dictionories. i.e. tuple[dict, dict]
    """
    matched_keywords_by_cat_dict={}
    score_dict={}

    cnt_cols = keywords_df.shape[1]
    
    for col_idx in range(0, cnt_cols):
        keyword_list=list(keywords_df.iloc[:,col_idx])
        matched_keywords=[]
        parent_cat=0
        for j in range(0,len(tokens)):
            token = tokens[j]
            if token in keyword_list:
                parent_cat= parent_cat + 1
                matched_keywords.append(token)
                parent_cat_name = keywords_df.columns[col_idx]
                matched_keywords_by_cat_dict[parent_cat_name]=matched_keywords
                score_dict[parent_cat_name]=parent_cat
    
    return matched_keywords_by_cat_dict, score_dict

我打电话给build_score_dict,如下图

third_level_closing=load_excel(input_dir+'third_level_keywords.xlsx',sheet_name='closing')     
_, level3_score_dict = build_score_dict(third_level_closing, tokens)

Pylance 在 VSCode 中给我以下警告/错误。这里发生了什么以及如何解决?

Argument of type "Series[Dtype]" cannot be assigned to parameter "keywords_df" of type "DataFrame" in function "build_score_dict"
  "Series[Dtype]" is incompatible with "DataFrame"Pylance (reportGeneralTypeIssues)

【问题讨论】:

    标签: python python-3.x pandas dataframe pylance


    【解决方案1】:

    解决方法

    如果您在调用 apply 时给 axis 一个值,它应该可以解决问题:

    def load_excel(file_path: str, sheet_name: str = ''):
        if sheet_name == '':
            df = pd.read_excel(file_path).fillna('').apply(lambda x: x.astype(str).str.lower(), axis='index')
        else:
            df = pd.read_excel(file_path, sheet_name).fillna('').apply(lambda x: x.astype(str).str.lower(), axis='index')
            
        return df
    

    说明

    如果您将类型信息添加到函数load_excel 的返回值,您将看到类型检查器将df 视为Series 而不是DataFrame

    如果我们编写如下函数代码,我们可以很快发现apply方法是问题的根源:

    def load_excel(file_path: str, sheet_name: str = "") -> pd.DataFrame:
        if sheet_name == "":
            df: pd.DataFrame = pd.read_excel(file_path)
        else:
            df: pd.DataFrame = pd.read_excel(file_path, sheet_name)
    
        df = df.fillna("")
        df = df.apply(lambda x: x.astype(str).str.lower())
    
        return df
    

    如果我们在apply 上按住 VSCode(在 Windows 上),我们可以看到以下内容:

    这表明,如果apply 方法接收的唯一参数是f,则类型检查器无法说出您想要的apply 方法的哪个版本。似乎 Pylance 实现适用于它找到的第一个定义,这就是我猜为什么你最终会返回 apply 假定为 Series。当您添加 axis 参数时,类型检查器现在可以检查返回 DataFrame 的第二个定义。

    【讨论】:

      猜你喜欢
      • 2021-09-15
      • 2021-10-18
      • 2020-10-11
      • 2019-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      • 2019-10-30
      相关资源
      最近更新 更多