Piyush S. Wanare
Piyush S. Wanare

Reputation: 4933

Pandas how to find position of cell contains sub-string

Example:

Price   | Rate p/lot |  Total Comm|
 947.2      1.25        BAM 1.25

 129.3      2.1         $ 1.25

 161.69     $ 0.8         CAD 2.00

If I have search for ['$','CAD']:-

Expected output:-

[(1, 2), (2, 1),(2,2)]

Upvotes: 1

Views: 57

Answers (3)

Lambda
Lambda

Reputation: 1392

Use str.contains:

df = df.astype(str)

from itertools import product
result = reduce(lambda x,y:x+y, [list(product([i],list(df.iloc[:,i][df.iloc[:,i].str.contains('\$|CAD')].index))) for i in range(len(df.columns))])

Output

[(1, 2), (2, 1), (2, 2)]

Upvotes: 1

jezrael
jezrael

Reputation: 863226

You can use in with applymap:

i, j = (df.applymap(lambda x: '$' in str(x))).values.nonzero()
t = list(zip(i, j))
print (t)
[(1, 2), (2, 1)]

i, j = (df.applymap(lambda x: any(y for y in L if y in str(x)))).values.nonzero()
#another solution
#i, j = (df.applymap(lambda x: any(s in str(x) for s in L))).values.nonzero()
t = list(zip(i, j))
print (t)

[(1, 2), (2, 1), (2, 2)]

Upvotes: 1

Piyush S. Wanare
Piyush S. Wanare

Reputation: 4933

Sorry, find solution like this,It may help someone

import pandas as pd

df = pd.DataFrame([[947.2, 1.25, 'BAM 1.25'],
                   [129.3, 2.1, '$ 1.25'],
                   [161.69, '0.8 $', 'CAD 2.00']],
                  columns=['Price', 'Rate p/lot', 'Total Comm'])


row, column = (df.applymap(lambda x: x if any(s in str(x) for s in ['$','CAD']) else None )).values.nonzero()
t = list(zip(row,column))

Upvotes: 1

Related Questions