使用copy()之后的SettingWithCopyWarning

时间:2019-03-17 06:22:41

标签: python pandas copy

我有如下代码。

@Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
    messages.simpTypeMatchers(SimpMessageType.CONNECT, SimpMessageType.SUBSCRIBE, SimpMessageType.HEARTBEAT,
            SimpMessageType.UNSUBSCRIBE, SimpMessageType.DISCONNECT).permitAll();
}

它给了我以下信息

import pandas as pd
import numpy as np
data = [['Alex',10,5,0],['Bob',12,4,1],['Clarke',13,6,0],['brke',15,1,0]]
df = pd.DataFrame(data,columns=['Name','Age','weight','class'],dtype=float) 

df_numeric=df.select_dtypes(include='number')#, exclude=None)[source]
df_non_numeric=df.select_dtypes(exclude='number')

df_non_numeric['class']=df_numeric['class'].copy()

我想让__main__:1: 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 独立于df_non_numeric

我根据其他帖子中的建议使用了df_numeric

我如何避免该消息?

1 个答案:

答案 0 :(得分:2)

我认为您需要copy,因为DataFrame.select_dtypes是切片操作,按列类型进行过滤,请检查Question 3

df_numeric=df.select_dtypes(include='number').copy()
df_non_numeric=df.select_dtypes(exclude='number').copy()

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