【问题标题】:Split() not working as intended #SettingWithCopyWarning , unable to understand the errorSplit() 未按预期工作 #SettingWithCopyWarning ,无法理解错误
【发布时间】:2019-09-25 22:54:22
【问题描述】:

我正在处理一个奇怪的错误,这段代码之前可以运行(之前运行的代码,几个小时前),但现在不行了。

import numpy as np   
import pandas as pd 
​df = pd.read_csv('nlp_monta.csv') 
df['Text 2'] = pd.Series(map(lambda x: str(x).replace("^"," "), df['Text']))
​i=0;
for row in df['Text 2']:
    df.iloc[i]['Text 2'] = set(row.split())    # This isn't giving unique words 
    i=i+1                                      #earlier it was 

警告,尽管代码正在运行 - Image of results

C:\Users\ishanna\AppData\Local\Continuum\anaconda3\lib\site->packages\ipykernel_launcher.py:2: SettingWithCopyWarning: 正在尝试在 DataFrame 中的切片副本上设置值

请参阅文档中的注意事项:http://pandas.pydata.org/pandas->docs/stable/indexing.html#indexing-view-versus-copy

【问题讨论】:

  • 请说明您的问题。另外,在您的情况下,“较早”是什么意思?
  • @Shijith : 问题在于 split() 而不是 lambda 函数
  • 您看到的警告告诉您df.iloc[i]['Text 2'] = set(row.split()) 可能实际上并未修改您的dfdf.iloc[i] 返回数据框的 view 并且该行的其余部分正在修改此视图(而不是原始数据框)。
  • @michcio1234 - '较早,表示代码的较早运行,编辑相同的问题

标签: python dataframe


【解决方案1】:

正如 cmets 中所讨论的,问题似乎在于 df.iloc[i]['Text 2'] = set(row.split())

SettingWithCopyWarning 告诉您df.iloc[i] 可能会返回您的数据框的视图,并且该行的其余部分正在修改此视图(而不是原始数据框)。

遍历行并不是一个好主意。相反,您可以尝试另一个map(虽然我没有测试过):

df['Text 2'] = df['Text 2'].str.split().map(set)

了解字符串访问器here

【讨论】:

  • 谢谢,这对我有很大帮助,对你的回答表示赞同,但由于我的声誉低于 15,所以不会显示
  • @Ishan 我很高兴能帮上忙!如果它解决了您的问题,您可以将答案标记为已接受。
猜你喜欢
  • 2011-02-28
  • 1970-01-01
  • 2023-03-05
  • 2021-11-16
  • 2015-03-25
  • 1970-01-01
  • 2023-01-11
  • 1970-01-01
  • 2019-06-26
相关资源
最近更新 更多