A value is trying to be set on a copy of a slice from a DataFrame
程序员文章站
2023-04-04 08:38:11
import pandas as pddef test1(): data = [{'id':1,'name': '华为'},{'id':2,'name': '荣耀'}] frame = pd.DataFrame(data) for index in frame.index: # frame['name'][index] = '华为' #这样写报错误 frame.loc[index,'name'] = '华为' #这样写不报错误def test2()...
import pandas as pd
def test1():
data = [{'id':1,'name': '华为'},{'id':2,'name': '荣耀'}]
frame = pd.DataFrame(data)
for index in frame.index:
# frame['name'][index] = '华为' #这样写报错误
frame.loc[index,'name'] = '华为' #这样写不报错误
def test2():
data = [{'id':'1','name': '华为'},{'id':'2','name': '荣耀'}]
frame = pd.DataFrame(data)
for index in frame.index:
frame['name'][index] = '华为' #这样写不报错误 可能因为frame中都是object类型吧
frame.loc[index,'name'] = '华为' #这样写不报错误
def test3():
data = [{'name': '华为','rate':9.9},{'name': '荣耀','rate':9.5}]
frame = pd.DataFrame(data)
for index in frame.index:
# frame['name'][index] = '华为' #这样写报错误
frame.loc[index,'name'] = '华为' #这样写不报错误
if __name__ == '__main__':
test1()
test2()
test3()
使用frame.loc[index,'name']
就没有问题了。
type(frame)
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2 entries, 0 to 1
Data columns (total 3 columns):
id 2 non-null int64
rate 1 non-null float64
name 2 non-null object
dtypes: float64(1), int64(1), object(1)
memory usage: 128.0+ bytes
.\test.py:34: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
本文地址:https://blog.csdn.net/zycdn/article/details/107361720
上一篇: 用户消费行为分析
下一篇: python 制作 多种 词云