Skip to content

error: Argument 1 to "astype" of "DataFrame" has incompatible type "Dict[str, str]" [arg-type] #411

Closed
@randolf-scholz

Description

@randolf-scholz
import pandas as pd

df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
columns_types = {"a" : "int", "b" : "float"}
df = df.astype(columns_types)  # ✘ raises [arg-type]

Context:

error: Argument 1 to "astype" of "DataFrame" has incompatible type "Dict[str, str]"; expected
"Union[str, Union[ExtensionDtype, Union[str, dtype[generic], Type[str], Type[complex], Type[bool], Type[object]]], Dict[str, Union[str, Union[ExtensionDtype, Union[str, dtype[generic], Type[str], Type[complex], Type[bool], Type[object]]]]]]"  [arg-type]
    df = df.astype(columns_types)  # ✘ raises [arg-type]
                   ^~~~~~~~~~~~~
note: "Dict" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance
note: Consider using "Mapping" instead, which is covariant in the value type

Suggestion:

def astype(
self,
dtype: _str | Dtype | dict[_str, _str | Dtype],
copy: _bool = ...,
errors: _str = ...,
) -> DataFrame: ...

needs to be replaced with

    def astype(
        self,
        dtype: _str | Dtype | Mapping[_str, _str | Dtype],
        copy: _bool = ...,
        errors: _str = ...,
    ) -> DataFrame: ...

Please complete the following information:

  • python 3.10.6
  • mypy 0.982
  • pandas 1.5.1
  • pandas-stubs 1.5.1.221024

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions