python astype(str) 给出 SettingWithCopyWarning 并请求我使用 loc [英] python astype(str) gives SettingWithCopyWarning and requests I use loc
问题描述
使用这行简单的代码,我不断收到一个 SettingWithCopyWarning 错误,并贯穿我的整个代码.
Using this simple line of code, I keep on getting a SettingWithCopyWarning error that than carries through my whole code.
#make email a string
df['Email Address'] = df['Email Address'].astype(str)
C:\Users\xxx\AppData\Local\Continuum\Anaconda2\lib\site-packages\ipykernel\__main__.py:2: 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
from ipykernel import kernelapp as app
我浏览了文档,但无法使其与 loc 一起使用.下面的代码是错误的.
I went through the documentation, but can't make it work with loc. The code below is wrong.
df.loc['Email Address'] = df.loc['Email Address'].astype(str)
如果这是一个重复的问题,请原谅 - 我在 stackoverflow 上搜索过,但找不到解决 loc 和 astype 的问题.
Please excuse if this is a duplicate question - I searched it on stackoverflow, but couldn't find one that addresses loc and astype.
推荐答案
您的问题不在于您如何进行分配.它与分配之前的数据帧有关.在分配之前的某个时间点,您创建了 df
以使其成为另一个数据帧的视图.您可以使用 bool(df.is_copy)
Your issue isn't with how you are making the assignment. It is with the dataframe prior to assignment. At some point prior to the assignment, you created df
in such a way that it became a view into another dataframe. You can verify this with bool(df.is_copy)
如果您认为 df
是一个单独的东西,与其他数据帧中的数据没有链接...
If you are ok with df
being a separate thing with no linkages to data in other dataframes...
df = df.copy()
然后继续进行分配.
这篇关于python astype(str) 给出 SettingWithCopyWarning 并请求我使用 loc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!