Zesty Dragon
Zesty Dragon

Reputation: 561

Python:How find index of element in column with some condition

This is my dataset

import pandas as pd
df={'A':['1@1','2,3','3,4',5]}
df=pd.DataFrame(df1)
df
A
0   1@1
1   2,3
2   3,4
3   5

I want to find index of data in column A which have ","

I tried this code but it is not working

Index=[]
for i in df["A"]:
    if ("," in i):
        Index.append(df["A"][i].index)
    else:
        continue

Upvotes: 3

Views: 788

Answers (2)

The problem in your code is not with the for-loop, but with the definition of df. You have defined df to contain both integers and strings-- and are trying to obtain the commas based on string manipulation,which is throwing an error. The proper definition of df would be --

df={'A':['1@1','2,3','3,4','5']}

After this, your code should work fine :)

Edit:

In case you want to stick with the dictionary df, define the for loop as--

for i in df["A"]:
    i=str(i)
    if ("," in i):
        Index.append(df["A"][i].index)
    else:
        continue

Upvotes: 1

jezrael
jezrael

Reputation: 863611

Use boolean indexing with index and for test subtring use Series.str.contains:

Index = df.index[df["A"].str.contains(',', na=False)].tolist()
print (Index)
[1, 2]

If need also not matched values save mask to variable and for non matched index values invert mask by ~:

mask = df["A"].str.contains(',', na=False)
Index1 = df.index[mask].tolist()
print (Index1)
[1, 2]

Index2 = df.index[~mask].tolist()
print (Index2)
[0, 3]

Upvotes: 4

Related Questions