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



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

试图在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

最新更新