3

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

2 Answers 2

4

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]
Sign up to request clarification or add additional context in comments.

1 Comment

i also wanted index which do not have ","
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.