使用pandas进行操作SettingWithCopyWarning

时间:2016-07-01 13:43:01

标签: python pandas dataframe chained-assignment

我尝试delete某些列并使用

转换列中的某些值
df2.drop(df2.columns[[0, 1, 3]], axis=1, inplace=True)
df2['date'] = df2['date'].map(lambda x: str(x)[1:])
df2['date'] = df2['date'].str.replace(':', ' ', 1)
df2['date'] = pd.to_datetime(df2['date'])

以及所有这个字符串我得到了

  df2.drop(df2.columns[[0, 1, 3]], axis=1, inplace=True)
C:/Users/����� �����������/Desktop/projects/youtube_log/filter.py:11: 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

那里有什么问题?

1 个答案:

答案 0 :(得分:10)

您的df2是另一个数据帧的片段。您需要在尝试df2 = df2.copy()

之前使用drop明确复制它

考虑以下数据框:

import pandas as pd
import numpy as np


df1 = pd.DataFrame(np.arange(20).reshape(4, 5), list('abcd'), list('ABCDE'))

df1

enter image description here

让我为df1分配df2

df2 = df1[['A', 'C']]

enter image description here

df2现在是df1的一部分,如果我们尝试更改SettingWithCopyWarning中的内容,则应触发那些讨厌的df2。我们来看看。

df2.drop('c')

enter image description here

没问题。怎么样:

df2.drop('c', inplace=True)

它是:

enter image description here

问题是pandas试图提高效率并跟踪df2指向与df1相同的数据。它保留了这种关系。警告告诉您,您不应该尝试通过切片混淆原始数据帧。

请注意,当我们查看df2时,行' c'已被放弃。

df2

enter image description here

看着df1我们看到那行' c'还在那里。

df1

enter image description here

pandas制作了df2的副本,然后放弃了行' c'。这可能与我们的意图可能不一致,我们的意图是df2切片并指向与df1相同的数据。所以大熊猫警告我们。

要看不到警告,请自行制作副本。

df2 = df2.copy()
# or
df2 = df1[['A', 'C']].copy()