using pandas to find the string from a column

Viewed 106

I am a very beginner in programming and trying to learn to code. so please bear with my bad coding. I am using pandas to find a string from a column (Combinations column in the below code ) in the data frame and print the entire row containing the string . Find the code below. Basically I need to find all the instances where the string occurs , and print the entire row .find my code below . I am not able to figure out how to find that particular instance of the column and print it .

 import pandas as pd 
data = pd.read_csv("signallervalues.csv",index_col=False) 
data.head()
data['col1'] = data['col1'].astype(str)
data['col2'] = data['col2'].astype(str)
data['col3'] = data['col3'].astype(str)
data['col4'] = data['col4'].astype(str)
data['col5']= data['col5'].astype(str)
data.head()

combinations= data['Col1']+data['col2'] + data['col3'] + data['col4'] + data['col5']
data['combinations']= combinations
print(data.head())

list_of_combinations = data['combinations'].to_list()
print(list_of_combinations)

for i in list_of_combinations:
    if data['combinations'].str.contains(i).any():
        print(i+ 'data occurs in row' )
        # I need to print the row containing the string here 
    else:
        print(i +'is occuring only once')
  

my data frame looks like this

enter image description here

1 Answers
import pandas as pd
data=pd.DataFrame()

# recreating your data (more or less)

data['signaller']= pd.Series(['ciao', 'ciao', 'ciao'])
data['col6']= pd.Series(['-1-11-11', '11', '-1-11-11'])

list_of_combinations=['11', '-1-11-11']


data.reset_index(inplace=True)

# group by the values of column 6 and counting how many times they occur
g=data.groupby('col6')['index']


count= pd.DataFrame(g.count()) 


count=count.rename(columns={'index':'occurences'})
count.reset_index(inplace=True)

# create a df that keeps only the rows in the list 'list_of_combinations'
count[~count['col6'].isin(list_of_combinations)== False]

My result

enter image description here

Related