即使在使用 .loc 之后,仍尝试在 DataFrame 警告的切片副本上设置值

2024-01-11

我收到警告“

 C:\Python27\lib\site-packages\pandas\core\indexing.py:411: 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 the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self.obj[item] = s" 

尽管按照文档中的建议我正在使用 df.loc ?

def sentenceInReview(df):
    tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
    print "size of df: " + str(df.size)
    df.loc[: ,'review_text'] = df.review_text.map(lambda x: tokenizer.tokenize(x))

    print df[:3]

我今天早些时候遇到了这个问题,这个问题与 Python 在函数/分配变量等之间传递“对象引用”的方式有关。

与 R 不同,在 python 中将现有数据帧分配给新变量不会进行复制,因此对“新”数据帧的任何操作仍然是对原始基础数据的引用。

解决这个问题的方法是进行深度复制(see docs https://docs.python.org/3/library/copy.html) 每当您尝试返回某物的副本时。看:

import pandas as pd
data = [1, 2, 3, 4, 5]
df = pd.DataFrame(data, columns = {'num'})
dfh = df.head(3)  # This assignment doesn't actually make a copy
dfh.loc[:,'num'] = dfh['num'].apply(lambda x: x + 1)
# This will throw you the error

# Use deepcopy function provided in the default package 'copy' 
import copy
df_copy = copy.deepcopy(df.head(3))
df_copy.loc[:,'num'] = df_copy['num'].apply(lambda x: x + 1)
# Making a deep copy breaks the reference to the original df. Hence, no more errors.

这是一个关于这个话题的更多内容 https://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/这或许可以解释 Python 做得更好的方式。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

即使在使用 .loc 之后,仍尝试在 DataFrame 警告的切片副本上设置值 的相关文章

随机推荐