警告:A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col

问题:

import pandas as pd

创建DataFrame对象A。

A = pd.DataFrame([['a1','b1','c1'], ['a2','b2','c2'],['a3','b3','c3']], columns = ['a', 'b', 'c'])
A

警告:A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_第1张图片
将A[‘a’] == 'a1’的行赋值于B。

B = A.loc[A['a'] == 'a1']
B

输出B
更改B值,此时被警告。

B[0] = 1
B

警告:A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_第2张图片

解决:

因为B此时为A的一个切片副本,pandas不知道是在副本上更改还是在原数据A上更改,所以将A.loc[A[‘a’] == ‘a1’]进行copy,使得B变为单独的个体,不再是切片副本。

B = A.loc[A['a'] == 'a1']

改为

B = A.loc[A['a'] == 'a1'].copy()

你可能感兴趣的:(python笔记,python)