【问题标题】:Resolving Issue with "Copy of a Slice from a DataFrame"解决“从数据帧复制切片”的问题
【发布时间】:2019-12-14 19:26:07
【问题描述】:

下面是一段代码,我喜欢和cmets一起解释。脚本的主要目的:打开/创建一个 csv 并在最后一个位置继续一个脚本。在脚本运行时,请确保将逐行写入 Dataframe,以免丢失任何已处理的数据。

data = pd.read_csv('input.csv', sep=',')

...

with open('output.csv', 'a+') as f:

# Continue script where it stopped last
pos = len(f.readlines()[1:])
data = data.iloc[pos:]

try:
    # Get two values from a function, write into two columns
    # progress_apply shows the progress (can be improved though)
    data[['city', 'country']] = data.progress_apply(func, axis=1, result_type='expand')
    # Append data to output.csv, but only add header for first entry
    data.to_csv(f, mode='a', header=f.tell()==0, encoding='utf-8', index=False)

except:
    print('Error at position {}.'.format(pos))
    pass

脚本完成处理后,会打印:

SettingWithCopyWarning:试图在一个副本上设置一个值 从 DataFrame 切片。尝试使用 .loc[row_indexer,col_indexer] = 取而代之的价值

我该如何解决这个问题,即代码有什么问题? 感谢您的帮助!

【问题讨论】:

    标签: python csv dataframe append


    【解决方案1】:

    由于位置参数,这是一个警告,并导致链式分配,通常,警告表明操作可能没有按预期工作。您可以通过在 loc[:],

    之前添加以下行来关闭警告
    pd.set_option('mode.chained_assignment', None)
    

    【讨论】:

    • 好的,然后我会取消警告。但是我可以确定操作没问题,还是有更好的方法? output.csv 看起来不错。如果这很重要,它也是'iloc',而不是'loc'。我认为错误可能就在那里。
    • 对我来说,您编写的代码看起来不错,iloc 期望 columnindex 100% 确定,但在您的情况下,您在最后一行之后添加一行,所以我认为应该很好.另外,您是否尝试将增量数据添加到读取的数据帧?
    • 请问,什么是“增量数据”?但是,是的,检查了输出,一切看起来都很好。
    • 我的意思是增量数据
    猜你喜欢
    • 2012-02-01
    • 2019-10-29
    • 2021-04-02
    • 2013-07-24
    • 2018-08-16
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 2019-05-01
    相关资源
    最近更新 更多