当我运行此代码时,我收到警告。我尝试了我能想到的所有可能的解决方案,但无法摆脱它。请帮忙!
尝试在 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/