matan
matan

Reputation: 461

how to use contains when: AttributeError: 'str' object has no attribute 'contains'

i like to do loop and check if cell contains "Ac" or "Vt string

that is my df

data={"col1":[2,3,4,5],
"col2":[4,2,4,6],
"col3":[7,6,9,11],
"col4":[14,11,22,8],
"name":["Acsd","Adgf","Vty","Acdf"],
"multi":[1.4,2.5,1.6,2.2]}
df=pd.DataFrame.from_dict(data)
print(df)

i try this :

for count1, i in enumerate(df["col1"]):
    if df.at[i, "name"].contains("Ac|Vt"):
        print("good")

and i got that error

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

how can i use contains that way?

Upvotes: 0

Views: 3129

Answers (3)

sushanth
sushanth

Reputation: 8302

Let's try using DataFrame.iterrows,

for _, j in df.iterrows():
    if "Ac" in j['name'] or "Vt" in j['name']:
        print('Good')

Upvotes: 2

Hryhorii Pavlenko
Hryhorii Pavlenko

Reputation: 3910

You could avoid using for loop altogether.

Why not just use df["name"].str.contains("Ac|Vt")?

You could add the result as a separate column too:

df.loc[df["name"].str.contains("Ac|Vt"), "status"] = "good"

Upvotes: 3

Abhilash Awasthi
Abhilash Awasthi

Reputation: 797

No need to do in loop.

df.loc[(df.name.str.contains('Ac')|df.name.str.contains('Vt'))] 

Upvotes: 1

Related Questions