【发布时间】: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