从数组中设置整个列时如何摆脱就地 FutureWarning?

lum*_*ric 24 python pandas

在 pandas v.1.5.0 中,添加了一个新警告,当从不同 dtype 的数组设置列时会显示该警告。当使用 时,通知FutureWarning有关计划的语义更改iloc:更改将在未来版本中就地完成。变更日志指示如何获取旧行为,但没有提示如何处理这种情况,而就地操作实际上是正确的选择。

更改日志中的示例:

df = pd.DataFrame({'price': [11.1, 12.2]}, index=['book1', 'book2'])
original_prices = df['price']
new_prices = np.array([98, 99])
df.iloc[:, 0] = new_prices
df.iloc[:, 0]
Run Code Online (Sandbox Code Playgroud)

这是警告,在 pandas 1.5.0 中打印:

FutureWarning:在未来版本中,df.iloc[:, i] = newvals将尝试就地设置值,而不是始终设置新数组。要保留旧行为,请使用或df[df.columns[i]] = newvals,如果列不唯一,df.isetitem(i, newvals)

如果我不关心是否就地,但想摆脱警告,如何摆脱警告?我应该明确更改 dtype 吗?我真的需要每次需要使用此功能时都收到警告吗?难道就没有更好的办法吗?

lum*_*ric 8

我没有找到比使用模块抑制警告更好的方法warnings:

import numpy as np
import pandas as pd
import warnings

df = pd.DataFrame({"price": [11.1, 12.2]}, index=["book1", "book2"])
original_prices = df["price"]
new_prices = np.array([98, 99])
with warnings.catch_warnings():
    # Setting values in-place is fine, ignore the warning in Pandas >= 1.5.0
    # This can be removed, if Pandas 1.5.0 does not need to be supported any longer.
    # See also: /sf/ask/5184015721/
    warnings.filterwarnings(
        "ignore",
        category=FutureWarning,
        message=(
            ".*will attempt to set the values inplace instead of always setting a new array. "
            "To retain the old behavior, use either.*"
        ),
    )

    df.iloc[:, 0] = new_prices

df.iloc[:, 0]
Run Code Online (Sandbox Code Playgroud)


Alp*_*ino 6

正如更改日志所述,当从具有不同 dtype 的数组中设置整个列时,会打印警告,因此调整 dtype 是使其静音的一种方法:

df = pd.DataFrame({'price': [11.1, 12.2]}, index=['book1', 'book2'])
original_prices = df['price']
new_prices = np.array([98, 99]).astype(float)
df.iloc[:, 0] = new_prices
df.iloc[:, 0]
Run Code Online (Sandbox Code Playgroud)

请注意附加的.astype(float). 不是一个理想的解决方案,而是一个解决方案。

  • 因为 `.astype(float)` 方法是您在现实生活示例中执行的操作,其中 `[98, 99]` 被替换为具有未知条目的数组 `x`。 (3认同)