在 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 吗?我真的需要每次需要使用此功能时都收到警告吗?难道就没有更好的办法吗?
我没有找到比使用模块抑制警告更好的方法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)
正如更改日志所述,当从具有不同 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). 不是一个理想的解决方案,而是一个解决方案。
| 归档时间: |
|
| 查看次数: |
13381 次 |
| 最近记录: |