
[英]Find index location of first occurrence of a specific partial string in pandas dataframe
[英]Find the index of first occurrence in DataFrame
提示:本站为国内最大中英文翻译问答网站,提供中英文对照查看,鼠标放在中文字句上可显示英文原文。
我有一个如下所示的数据框:
0 1 2 3 4 5 6
0 a(A) b c c d a a
1 b h w k d c(A) k
2 g e(A) s g h s f
3 f d s h(A) c w n
4 e g s b c e w
我想得到每列中包含(A)
的单元格的索引。
0 0
1 2
2 NaN
3 3
4 NaN
5 1
6 NaN
我尝试了这段代码,但结果并没有达到我的预期。
df.apply(lambda x: (x.str.contains(r'(A)')==True).idxmax(), axis=0)
结果如下所示:
0 0
1 2
2 0
3 3
4 0
5 1
6 0
我认为如果该列中没有(A)
,它将返回第一个索引。
我该如何解决?
使用Series.where
为默认设置缺少覆盖默认值0
的值DataFrame.idxmax
:
mask = df.apply(lambda x: x.str.contains('A'))
s1 = mask.idxmax().where(mask.any())
print (s1)
0 0.0
1 2.0
2 NaN
3 3.0
4 NaN
5 1.0
6 NaN
dtype: float64
您可以执行您正在执行的操作但显式检查行是否包含任何匹配项:
In [51]: pred = df.applymap(lambda x: '(A)' in x)
In [52]: pred.idxmax() * np.where(pred.any(), 1, np.nan)
Out[52]:
0 0.0
1 2.0
2 NaN
3 3.0
4 NaN
5 1.0
6 NaN
dtype: float64
或者,直接使用DataFrame.where
:
In [211]: pred.where(pred).idxmax()
Out[211]:
0 0.0
1 2.0
2 NaN
3 3.0
4 NaN
5 1.0
6 NaN
dtype: float64
稍微有些单行的是在身份上使用DataFrame.where
:
In [78]: df.apply(lambda x: x.str.contains('A')).where(lambda x: x).idxmax()
Out[78]:
0 0.0
1 2.0
2 NaN
3 3.0
4 NaN
5 1.0
6 NaN
在apply
的末尾添加if条件:
>>> df.apply(lambda x: x.str.contains('A').idxmax() if 'A' in x[x.str.contains('A').idxmax()] else np.nan)
0 0.0
1 2.0
2 NaN
3 3.0
4 NaN
5 1.0
6 NaN
dtype: float64
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.