a function that uses contains() to determine whether Python contains a specific string

Asked 1 years ago, Updated 1 years ago, 398 views

For the string item train['name'] in Python, I would like to create a separate item with "1" if it contains a specific string (e.g., "aaaa"), or "0" if it does not contain it (train['test']).At that time, I tried to create the following functions (kansu1 and kansu2) and set them with the apply function, but could you tell me where the problem is because it didn't work?

def test_kansu1(s):
    ifs.contains('aaa'):
        return1
    else:
        return 0

train['test'] = train['name'].apply(lambdax:test_kansu1(x))

-->AttributeError: 'str' object has no attribute'str'

def test_kansu2(s):
    ifs.str.contains('aaa'):
        return1
    else:
        return 0

train['test'] = train['name'].apply(lambdax:test_kansu2(x))

-->AttributeError: 'str' object has no attribute' contains'

python3

2023-01-02 23:48

1 Answers

def test_kansu1(s):
    # ifs.contains('aaa'): #< -- Error because str instance does not have content method
    if 'aaa'ins:
        return1
    else:
        return 0

def test_kansu2(s):
    # ifs.str.contains('aaa'):#<--Error because str type instance does not have attribute (attribute)
    if 'aaa'ins:
        return1
    else:
        return 0

pandas.Series.str.contains()

import pandas as pd

train=pd.DataFrame({
    'name': ['01_aaa', '02_bbb', '03_ccc', '04_ddd', '05_eee']
})

train['test'] = train['name'].str.contains('aaa')*1
print(train)

#      name test
# 001_aaa1
# 102_bbb0
# 203_cc0
# 304_ddd0
# 405_eee0


2023-01-03 02:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.