Pandas:如何处理 1.5.0 版本中 DataFrame.set_index 注释引入的 pylint 错误

问题描述 投票:0回答:1

当通过 [] 符号访问列时,dataframe 的 set_index 方法的注释导致 pylint 抛出错误。

这是因为 pylint 不知道,仅在 inplace=True 的情况下才返回 None。这可以通过

df.A
访问来解决,但无论哪种方式,在 inplace=True 的情况下都会失败。您能建议一下,如何最好地处理这个问题吗?

import pandas as pd

df = pd.DataFrame([{"A": 1, "B": 2}]).set_index("B")
print(df.A)  # this wokrs
print(df['A'])  # this throws an pylint error
python pandas pylint
1个回答
0
投票

首先,更多信息:

  • set_index()
    方法返回
    ( DataFrame | None )
  • df.A
    df['A']
    的type()都是
    panda.core.series.Series
df = pd.DataFrame([{"A": 1, "B": 2}]).set_index("B")
print(df.A)  # pylint: "A" is not a member of "None"
print(df['A'])  # pylint: Object of type "None" is not scriptable

由于

pylint
不知道你的索引是否返回一个值,它会抱怨它,即使在运行时,对于这种特殊情况,一切都很好。

您可以将语句分解为两行,并就地替换索引,因此

df
将保留为
DataFrame
:

df = pd.DataFrame([{"A": 1, "B": 2}])
df.set_index("B", inplace=True)  # df is still a DataFrame
print(df.A)  # No problem
print(df['A'])  # No problem
© www.soinside.com 2019 - 2024. All rights reserved.