gpt4 book ai didi

python - 警告 - 试图在切片的副本上设置值

转载 作者:太空宇宙 更新时间:2023-11-04 02:14:14 25 4
gpt4 key购买 nike

我在运行这段代码时收到警告。我尝试了所有我能想到的可能的解决方案,但无法摆脱它。请帮忙!

试图在 DataFrame 的切片副本上设置一个值。尝试使用 .loc[row_indexer,col_indexer] = value 代替

import math
task2_df['price_square'] = None
i = 0
for row in data.iterrows():
task2_df['price_square'].at[i] = math.pow(task2_df['price'][i],2)
i += 1

最佳答案

对于初学者,我没有看到您在 Pandas v0.19.2 上的错误(使用此答案底部的代码进行测试)。但这可能与解决您的问题无关。您应该避免在 Python 级循环中迭代行。 Pandas 使用的 NumPy 数组专为数值计算而设计:

df = pd.DataFrame({'price': [54.74, 12.34, 35.45, 51.31]})
df['price_square'] = df['price'].pow(2)

print(df)

price price_square
0 54.74 2996.4676
1 12.34 152.2756
2 35.45 1256.7025
3 51.31 2632.7161

在 Pandas v0.19.2 上测试,没有警告/错误:

import math

df = pd.DataFrame({'price': [54.74, 12.34, 35.45, 51.31]})
df['price_square'] = None
i = 0

for row in df.iterrows():
df['price_square'].at[i] = math.pow(df['price'][i],2)
i += 1

关于python - 警告 - 试图在切片的副本上设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53004973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com