Reputation: 4933
I have following data frame I want to find the index for cell which are starts with certain string.
Example :
Price | Rate p/lot | Total Comm|
947.2 1.25 BAM 1.25
129.3 2.1 NAD 1.25
161.69 0.8 CAD 2.00
If I have search for ['NAD']:-
Expected output:-
(1,2)
Upvotes: 4
Views: 1768
Reputation: 4933
For reference if anyone wants to fetch for position for cell contains substring.
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 ('$') in str(x) else None )).values.nonzero()
t = list(zip(row,column))
Upvotes: 0
Reputation: 164773
You can do this efficiently with numpy.argwhere
:
import pandas as pd, numpy as np
df = pd.DataFrame([[947.2, 1.25, 'BAM 1.25'],
[129.3, 2.1, 'NAD 1.25'],
[161.69, 0.8, 'CAD 2.00']],
columns=['Price', 'Rate p/lot', 'Total Comm'])
res = np.argwhere(df.values.astype('<U3') == 'NAD')
# array([[1, 2]], dtype=int64)
This gives you an array of coordinates where your condition is matched.
To get a single tuple:
res = next(map(tuple, np.argwhere(df.values.astype('<U3') == 'NAD')))
# (1, 2)
For a list of strings:
res = list(map(tuple, np.argwhere(np.logical_or.reduce(\
[df.values.astype('<U3') == i for i in np.array(['BAM', 'NAD'])]))))
Upvotes: 1
Reputation: 863226
Use applymap
with startswith
:
i, j = (df.applymap(lambda x: str(x).startswith('NAD'))).values.nonzero()
t = list(zip(i, j))
print (t)
[(1, 2)]
For list of input values use:
L = ['NAD','BAM']
i, j = (df.applymap(lambda x: str(x).startswith(tuple(L)))).values.nonzero()
t = list(zip(i, j))
print (t)
[(0, 2), (1, 2)]
Upvotes: 1