简体   繁体   English

SettingWithCopyWarning 尝试对 pandas dataframe 中的用户进行分类时

[英]SettingWithCopyWarning when trying to classify users in pandas dataframe

I am getting a SettingWithCopyWarning when trying to classify users in pandas dataframe,尝试对 pandas dataframe 中的用户进行分类时,我得到了 SettingWithCopyWarning,

I have a Dataframe that contains a 'user_id' column, that if it is contained in a determined list, it will give me a value and if not, then it will give me another我有一个 Dataframe 包含一个“user_id”列,如果它包含在一个确定的列表中,它会给我一个值,如果没有,那么它会给我另一个

In this case, I am trying to create a new column that given a determined condition, (if the id is in a list) the it will give me a 'male' string as a value in the new column, but if the id is not in the list it will give me a female, this is what I am trying:在这种情况下,我正在尝试创建一个给定条件的新列,(如果 id 在列表中)它会给我一个“男性”字符串作为新列中的值,但如果 id 是不在列表中它会给我一个女性,这就是我正在尝试的:

def select_user_type(df, male_list):
    types = {
        1: 'female',
        2: 'male'
    }
    search_column = 'user_id'
    df['user_sex'] = df.apply(lambda x: types[2] if x[search_column] in male_list else types[1], axis=1)
    return df

The error I get is the following我得到的错误如下

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

Example:例子:

male_list = [354, 899] #Example

output: output:

name    user_id   user_sex
Jane    890       female
Jean    899       male
Rita    708       female
John    354       male

Seems to work for me without issues.似乎为我工作没有问题。 However lets try;但是,让我们尝试;

def select_user_type(df, male_list):
    types = {
        1: 'female',
        2: 'male'
    }
    search_column = 'user_id'
    df = df.assign(user_sex=df.apply(lambda x: types[2] if x[search_column] in male_list else types[1], axis=1))
    return df

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM