Khine Sint
Khine Sint

Reputation: 13

search in iteration using python

I have two lists "OD_pair" and "OD_list". OD_pair = [ A B C]

OD_list = [ B B A B A B C]

I am writing a python search to count how many OD pairs repeated in the OD list and adding another column for the result. For example: I will take "A" from OD_pair, go to "OD_list", count how many "A"s are in "OD list" and return the number, and add it next to OD pair.

#take OD pair from moira data
OD_pair = df_moira['OD_pair'] #OD pair list
#loop ticket gate data and count how many OD pair appears in ticket gate data
OD_list = df_ticket_gate['OD_PAIRS'] # OD list
i = 0
while i < len(OD_pair): # go to OD pair list
    OD = OD_pair(i) # take an iteam to search
    j = 0
    for j in OD_list:
        sum(1 for OD_pair in OD_list if OD = OD_list(j)) # search the item in OD list and count
    i += 1

The result will look like this : OD_pair = [ A 2 B 4 C 1 ]

Upvotes: 1

Views: 42

Answers (2)

xxjjnn
xxjjnn

Reputation: 15239

A more general solution using pure python would be:

OD_pair = ['A','B','C']
OD_list = ['B','B','A','B','A','B','C']

results = {}
for val in OD_pair:
    results[val] = OD_list.count(val)
print(results)

which would give:

{'A': 2, 'B': 4, 'C': 1}

Though the code shown in the question suggests you're using pandas dataframes so the other solution is more useful in this specific case.

Upvotes: 0

Sainath
Sainath

Reputation: 74

If all you are looking for is getting the number of times an item is repeating in list of values. You can try using this:

df = pd.DataFrame({'A':[1,2,3,4]})
df1 = pd.DataFrame({'B':[2,1,2,3,1,2,3,1,3]})

OD_pair = df[['A']]

OD_list = df1['B'].value_counts().to_frame().reset_index()

Output = OD_pair.merge(OD_list,'left',left_on = 'A',right_on = 'index')[['A','B']]

print(Output)

Upvotes: 1

Related Questions