【问题标题】:Where does this pandas warning come from?这个熊猫警告来自哪里?
【发布时间】:2018-05-26 08:50:39
【问题描述】:

我有一个数据框。为了进行统计条件测试,我根据布尔列 ('mar') 将其分成两部分。我想使用两个表之间的计数比率来为其他列的每个组合添加一个表示“mar”列中真实值比例的列,如下所示。

>>> df_nomar
   alc  cig  mar  cnt
1    1    1    0  538
3    1    0    0  456
5    0    1    0   43
7    0    0    0  279

>>> df_mar
   alc  cig  mar  cnt
0    1    1    1  911
2    1    0    1   44
4    0    1    1    3
6    0    0    1    2
>>> df_mar.loc[:, 'prop'] = np.array(df_mar['cnt'])/(np.array(df_mar['cnt']) + np.array(df_nomar['cnt']))
/usr/local/lib/python3.5/dist-packages/pandas/core/indexing.py:296: 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

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self.obj[key] = _infer_fill_value(value)
/usr/local/lib/python3.5/dist-packages/pandas/core/indexing.py:476: 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

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self.obj[item] = s

>>> df_mar
   alc  cig  mar  cnt      prop
0    1    1    1  911  0.628709
2    1    0    1   44  0.088000
4    0    1    1    3  0.065217
6    0    0    1    2  0.007117

我已前往suggested page 调查警告。当我分配新列时,我使用df_mar.loc[:, 'prop'] = ... 的形式,正如建议的那样。

那么为什么我仍然收到此警告?

【问题讨论】:

标签: python python-3.x pandas dataframe chained-assignment


【解决方案1】:

如果DataFrames reset_index 的大小相同,您似乎需要对齐数据:

a = df_mar['cnt'].reset_index(drop=True)
b = df_nomar['cnt'].reset_index(drop=True)
df_mar['prop'] = (a/(a + b)).values

另一种解决方案是通过values 转换为numpy array

a = df_mar['cnt'].values
b = df_nomar['cnt'].values
df_mar['prop'] = a / (a + b)

print (df_mar)
   alc  cig  mar  cnt      prop
0    1    1    1  911  0.628709
2    1    0    1   44  0.088000
4    0    1    1    3  0.065217
6    0    0    1    2  0.007117

这个熊猫警告来自哪里

它显然来自上面的代码。如果过滤DataFrames 则需要copy:

df_nomar = df[df['mar'] == 0].copy()
df_mar = df[df['mar'] == 1].copy()

如果您稍后修改 df 中的值,您会发现修改不会传播回原始数据(df_nomardf_mar),并且 Pandas 会发出警告。

【讨论】:

  • 我在我的代码中转换为 np.array,虽然方法不同。使用 df[index].values 方式,警告仍然存在。
  • 我尝试了你的代码,没有任何警告,所以我猜问题出在上面的代码行中。
  • 也许你也可以从tutorials查看thismoderna pandas(寻找标题SettingWithCopy
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-04
  • 2021-11-14
  • 1970-01-01
  • 2019-08-03
  • 2013-03-13
  • 1970-01-01
相关资源
最近更新 更多