我有以下数据框我想找到以某些字符串开头的单元格的索引。
示例:
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
如果我搜索[' NAD']: -
预期产出: -
(1,2)
答案 0 :(得分:1)
将applymap
与startswith
:
i, j = (df.applymap(lambda x: str(x).startswith('NAD'))).values.nonzero()
t = list(zip(i, j))
print (t)
[(1, 2)]
对于输入值列表,请使用:
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)]
答案 1 :(得分:1)
您可以使用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)
这为您提供了一个匹配条件的坐标数组。
获得单个元组:
res = next(map(tuple, np.argwhere(df.values.astype('<U3') == 'NAD')))
# (1, 2)
获取字符串列表:
res = list(map(tuple, np.argwhere(np.logical_or.reduce(\
[df.values.astype('<U3') == i for i in np.array(['BAM', 'NAD'])]))))
答案 2 :(得分:0)
如果有人想要获取包含子字符串的单元格的位置,请参考。
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))