df[‘col_name’].astype(‘string’) raises error in pyright

  Kiến thức lập trình

I recently added pyright to my project and I’m facing this issue.

import pandas as pd

# Define the cleanup function
def cleanup(df: pd.DataFrame) -> pd.DataFrame:
    df['col_name_1'] = df['col_name_1'].astype('string')
    df = df.drop_duplicates(subset=['col_name_2'])
    return df

# Create a sample DataFrame
data = {'col_name_1': [1, 2, 3, 4, 5],
        'col_name_2': ['A', 'B', 'C', 'A', 'D']}
df = pd.DataFrame(data)
cleanup(df)

Errors:

error: "astype" is not a known member of "None" (reportOptionalMemberAccess)
error: Expression of type "DataFrame | None" cannot be assigned to declared type "DataFrame"

This code snippet works perfectly as expected. It’s just the pyright type mismatch that is an issue

1

LEAVE A COMMENT