红色字体是解决方案
# Setting multiple items using a mask
#使用.str.startswith('o') 指定批量赋值的位置
In [364]: mask = dfd['a'].str.startswith('o')
In [365]: dfd.loc[mask, 'c'] = 42
(从下内容机器翻译)
使用链接索引时,索引操作的顺序和类型将部分确定结果是原始对象中的切片,还是切片的副本。
pandas具有“复制警告”设置,因为分配给切片的副本通常不是故意的,而是链接索引返回预期切片所在的副本所导致的错误。
如果希望pandas或多或少信任对链接索引表达式的赋值,可以设置 mode.chained_assignment为以下值之一:
默认情况下,“警告”表示打印带有复印警告的设置。
“raise”表示pandas将提出一个设置,但你必须处理
切片副本的例外情况。
没有人会完全压制这些警告。
In [360]: dfb = pd.DataFrame({'a': ['one', 'one', 'two',
.....: 'three', 'two', 'one', 'six'],
.....: 'c': np.arange(7)})
.....:
# This will show the SettingWithCopyWarning
# but the frame values will be set
In [361]: dfb['c'][dfb['a'].str.startswith('o')] = 42
但是,这是在副本上运行的,将不起作用。
>>> pd.set_option('mode.chained_assignment','warn')
>>> dfb[dfb['a'].str.startswith('o')]['c'] = 42
Traceback (most recent call last)
...
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
在混合 dtype 框架的设置中,链式分配也可能突然出现。
注意
这些设置规则适用于所有 ..loc/.iloc
以下是对多个项目(使用 )和单个项目使用固定索引的推荐访问方法:.loc
mask
In [362]: dfc = pd.DataFrame({'a': ['one', 'one', 'two',
.....: 'three', 'two', 'one', 'six'],
.....: 'c': np.arange(7)})
.....:
In [363]: dfd = dfc.copy()
# Setting multiple items using a mask
In [364]: mask = dfd['a'].str.startswith('o')
In [365]: dfd.loc[mask, 'c'] = 42
In [366]: dfd
Out[366]:
a c
0 one 42
1 one 42
2 two 2
3 three 3
4 two 4
5 one 42
6 six 6
# Setting a single item
In [367]: dfd = dfc.copy()
In [368]: dfd.loc[2, 'a'] = 11
In [369]: dfd
Out[369]:
a c
0 one 0
1 one 1
2 11 2
3 three 3
4 two 4
5 one 5
6 six 6
以下情况有时可能有效,但不能保证,因此应避免:
In [370]: dfd = dfc.copy()
In [371]: dfd['a'][2] = 111
In [372]: dfd
Out[372]:
a c
0 one 0
1 one 1
2 111 2
3 three 3
4 two 4
5 one 5
6 six 6
最后,后续示例将根本不起作用,因此应避免:
>>> pd.set_option('mode.chained_assignment','raise')
>>> dfd.loc[0]['a'] = 1111
Traceback (most recent call last)
...
SettingWithCopyException:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead