即使在使用后,仍试图在数据帧警告的切片副本上设置值。

2024-04-27 15:36:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我收到了警告”

 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]

Tags: ofthetext警告pandasdfsizevalue
3条回答

尝试使用pd.Series插入值(data,index=index_list)

警告消息“A value is trying to be set on A copy of A slice from A DataFrame”的常见原因是:一个切片覆盖另一个切片! 例如:

dfA=dfB['x','y','z']
dfC=dfA['x','z']

“” 对于上述代码,您可能会收到这样的消息,因为dfC是dfA的一部分,而dfA是dfB的一部分。也就是说,dfC是另一个片dfA上的一个片,并且两者都链接到dfB。在这种情况下,无论您使用.copy()还是deepcopy或其他类似方式,它都不起作用:-( “”

解决方案:

dfA=dfB['x','y','z']
dfC=dfB['x','z']

希望上面的解释有帮助:-)

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

与say,R不同,在python中,为一个新变量分配一个现有的数据帧不会产生副本,因此对“new”数据帧的任何操作仍然是对原始底层数据的引用。

解决这个问题的方法是,每当您试图返回某个内容的副本时,都要生成一个深度副本(see docs)。见:

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.

这里有一个bit more on this topic可以解释Python做得更好的方式。

相关问题 更多 >