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

时间:2018-10-26 08:51:51

标签: python python-3.x pandas dataframe

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

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

isset

1 个答案:

答案 0 :(得分:2)

对于初学者来说,我看不到您在Pandas v0.19.2上的错误(此答案底部的代码经过测试)。但这可能与解决您的问题无关。您应该避免在Python级循环中迭代行。熊猫使用的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
相关问题