python--解决【Setting With Copy Warning】问题 问题解决:SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame

【问题描述】

在向DataFrame中按照一定条件添加一列时,会出现【Setting With Copy Warning】报错的问题

举例:

先建立一个示例数据框:

test_0 = {"id":[1,1,2,3,3,4,5,5],"price":[5,6,8,3,4,6,9,5],"amount":[1,1,2,1,1,1,2,1],"status":['sale','sale','no','no','sale','no','sale','no']}
test = pd.DataFrame(test_0)
test = test[['id','price','amount','status']]   #调整顺序
test 

得到的数据为:


现在想要加入一列“index”,赋值逻辑为:与“status”对应位置一致

n = 0
test['index'] = None
for id in test['id']:
    test['index'][n] = test['status'][n]
    n+=1
test

此时便发生【Setting With Copy Warning】报错(不影响程序运行,但是还是不想他出现,也担心真的会在之后产生问题鄙视


【解决方法】

先建立一个新的Series来存储这个新的数据,然后再插入到DataFrame中。

n = 0
index = pd.Series(test.shape[0])     #生成一个结构相似的Series
for id in test['id']:
    index[n] = test['status'][n]
    n+=1
test.insert(1,'index',index)
test

没报错!问题解决!

参考:

问题解决:SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame

(仅供个人学习,不负责任~~~~~~~~~~~~~~~~)

猜你喜欢

转载自blog.csdn.net/august1226/article/details/80664964
今日推荐