0

I was trying to open a csv file panda_try.csv. What i want to do is to compare the elements in the first two columns from the file and check if they are equal. If they are equal, I want to append it in a list called selfloop_appender and then calculate the length of list. But when i try to `print (selfloop_appender)', i donot get any output and error. Any help will be great.

import pandas as pd
df = pd.read_csv('/home/venkat/Desktop/panda_try.csv')
xy_data = df.iloc[:,0:2]

def self_loops(xy_data):
    selfloop_appender = []
    for i,j in xy_data:
        if i == j:
            selfloop_appender.append([i,j])
            print("the number of self_loops are:") + len(str(selfloop_appender))

    return selfloop_appender
self_loops(xy_data)

1 Answer 1

2

You can try nunique, if it equal to 1 , mean i=j.

xy_data[xy_data.nunique(1)==1].iloc[:,1].tolist()

Update

df=pd.DataFrame({'A':[1,2,3],'B':[1,2,6]})
df.nunique(1)
Out[440]: 
0    1
1    1
2    2
dtype: int64

If return 1 means A=B

Then we using eq(equal to ==) to slice the row we need

df[df.nunique(1).eq(1)]
Out[442]: 
   A  B
0  1  1
1  2  2
df[df.nunique(1).eq(1)].iloc[:,1]
Out[443]: 
0    1
1    2
Name: B, dtype: int64
df[df.nunique(1).eq(1)].iloc[:,1].tolist()
Out[444]: [1, 2]
Sign up to request clarification or add additional context in comments.

1 Comment

I am not able to understand, can u make the edit in the code?

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.