0

错误:AttributeError:“int”对象没有属性“isin”

问题:没有空值,在单独的代码块中工作。试图将R系列的数据类型修改为对象,错误:'str'对象没有属性'isin'

我错过了什么?

代码:

    X = [1, 2, 3, 4]
    if dg['RFM_Segment'] == '111':
        return 'Core'
    elif (dg['R'].isin(X) & dg['F'].isin([1]) & dg['M'].isin(X) & (dg['RFM_Segment'] != '111')).any():
        return 'Loyal'
    elif (dg['R'].isin(X) & dg['F'].isin(X) & dg['M'].isin([1]) & (dg['RFM_Segment'] != '111')).any():
        return 'Whales'
    elif (dg['R'].isin(X) & dg['F'].isin([1]) & dg['M'].isin([3,4])).any():
        return 'Promising'
    elif (dg['R'].isin([1]) & dg['F'].isin([4]) & dg['M'].isin(X)).any():
        return 'Rookies'
    elif (dg['R'].isin([4]) & dg['F'].isin([4]) & dg['M'].isin(X)).any():
        return 'Slipping'
    else:
        return 'NA'
    
dg['user_segment']= dg.apply(user_segment, axis= 1)
4

1 回答 1

0

我假设您不小心切断了代码片段的顶部,您在其中定义了user_segment.

问题在于您尝试使用apply. 请注意,apply 将在 上操作Series,而不是DataFrame. 因此,通过索引到系列的任何元素,您将不会收到一个Series对象(就像您在索引到 时一样DataFrame),而是一个给定列类型的对象(例如intstr)。一个例子:

import pandas as pd

X = ['a', 'c']
df = pd.DataFrame([['a', 'b'], ['c', 'd'], ['e', 'f']], columns=['col1', 'col2'])
df['col1'].isin(X)  # this works, because I'm applying `isin` on the entire column.


def test_apply(x):
    print(x['col1'].isin(X))
    return x

df.apply(test_apply, axis=1)  # this doesn't work, 
                              # because I'm applying `isin` on a non-pandas object, in 
                              # this example `str`

于 2022-01-02T19:59:45.263 回答