我想知道如何在尝试将str.lower()
应用于pandas数据帧中的列时处理SettingWithCopyWarning,以便我的所有数据(仅该列上的数据(都变为小写。
我的实际代码
df2["originator _ beliefs"] = df2["originator _ beliefs"].str.lower()
我的错误:
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
我的其他尝试:
df3["originator _ beliefs"] = df2.loc[df2["originator _ beliefs"].str.lower()]
df3["originator _ beliefs"] = df2["originator _ beliefs"].str.lower().copy()
我所尝试的只是将"中的所有项目小写;始祖信念
这是一个警告,而不是错误。在运行代码后检查df2["originator _ beliefs"]
;你应该看到它确实降低了你试图降低的列。警告是指你正在从推断的df1
(这就是df2
(更改切片的副本,如果你试图更改df1
,你就不会。有一些方法可以抑制警告,但这有点超出了问题的范围。
In [36]: df = pd.DataFrame([[1, 'a'], [2, 'b']], columns=['num', 'char'])
In [37]: df
Out[37]:
num char
0 1 a
1 2 b
In [38]: df1 = df[df.char == 'a']
In [39]: df1
Out[39]:
num char
0 1 a
In [40]: df1['char'] = df1['char'].str.upper()
<ipython-input-40-0ba8b77332da>: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: https://pandas.pydata.org/pandas-docs/stable/user_g
uide/indexing.html#returning-a-view-versus-a-copy
df1['char'] = df1['char'].str.upper()
In [41]: df1
Out[41]:
num char
0 1 A
In [42]: df
Out[42]:
num char
0 1 a
1 2 b
一定要查看文档以了解更多信息:https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy