[英]Pandas how to find position of cell startswith string
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']:- 如果我搜索['NAD']: -
Expected output:- 预期产量: -
(1,2)
Use applymap
with startswith
: 使用带有
startswith
applymap
:
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)]
You can do this efficiently with numpy.argwhere
: 您可以使用
numpy.argwhere
有效地执行此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'])]))))
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.