当前位置: 首页 > 工具软件 > Isona > 使用案例 >

A value is trying to be set on a copy of a slice from a DataFrame

师向文
2023-12-01

最近在做数据分析的时候,发现在Dataframe中插入一列之后会报这个错误

A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

源数据如下:

In [158]:data
Out[158]: 
            A           B    C  D
0  474.037241  317.492254    1  5
1         NaN  113.097304  466  5
2   72.738154  112.610778  268  5
3   92.114468   81.244514   44  5
4         NaN   80.851410  238  5
5   75.187579   70.767059  266  5
6   46.004532   61.677649  343  5
7   56.571745   58.176366   10  5
8         NaN   52.703629  420  5
9   21.195272   51.706517  158  5

插入即报错:

In [159]: data['E']=6
__main__:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

解决办法:利用Dataframe.insert函数插入停止报错// 或者直接在data前面加上 data=data.copy()

In [160]: data.insert(loc=0, column='F',value=6)

博文:Pandas 中 Insert函数 详解

 类似资料:

相关阅读

相关文章

相关问答