简体   繁体   English

Pandas:str.lower() 的 SettingWithCopyWarning

[英]Pandas: SettingWithCopyWarning for str.lower()

I want to know how to deal with SettingWithCopyWarning when trying to apply str.lower() to a column in pandas dataframe so all my data, only on that column gets lowercase.我想知道在尝试将str.lower()应用于 pandas dataframe 中的列时如何处理 SettingWithCopyWarning ,因此我的所有数据,仅在该列上变为小写。

My actual code我的实际代码

df2["originator _ beliefs"]  = df2["originator _ beliefs"].str.lower()

My error:我的错误:

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

My other attempts:我的其他尝试:

df3["originator _ beliefs"]  = df2.loc[df2["originator _ beliefs"].str.lower()]
df3["originator _ beliefs"]  = df2["originator _ beliefs"].str.lower().copy()

All I am trying is to lowercase all the items in "originator _ beliefs"我正在尝试的只是小写“创始人_信念”中的所有项目

It's a warning, not an error.这是一个警告,而不是错误。 Check df2["originator _ beliefs"] after you run your code;运行代码后检查df2["originator _ beliefs"] you should see that it did indeed lower the column you were attempting to.您应该看到它确实降低了您尝试的列。 The warning is referring to the fact that you are changing a copy of a slice from an inferred df1 (which is what df2 is) and that if you were trying to change df1 , you ain't gonna.警告指的是您正在从推断的df1 (这就是df2 )更改切片的副本,并且如果您尝试更改df1 ,那么您不会。 There are ways to suppress the warning, but that is a bit out of scope of the question.有一些方法可以抑制警告,但这有点超出问题的 scope 。

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

Definitely check out the docs for more info on this: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy一定要查看文档以获取更多信息: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM