关于SettingWithCopyWarning

在对DataFrame添加新列的时候时常会遇到SettingWithCopyWarning:

Google了一番,最后在stack overflow上找到了最恰当的用法。

  • 我使用的pandas的版本:
import pandas as pd
pd._version.get_versions()

"""
{'dirty': False,
 'error': None,
 'full-revisionid': 'a00154dcfe5057cb3fd86653172e74b6893e337d',
 'version': '0.22.0'}
"""
  • 在探索过程中尝试了以下两种写法,但均不能避免SettingWithCopyWarning:
df['new_column'] = ...
df.loc[:, 'new_column'] = ...
  • 正确姿势:
df = df.assign(new_column = ...)

Contents


本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。

知识共享许可协议