Issue w/ pandas.index.get_loc() when match is found, TypeError: ("'>' not supported between instances of 'NoneType' and 'str'", 'occurred at index 1')

Issue w/ pandas.index.get_loc() when match is found, TypeError: ("'>' not supported between instances of 'NoneType' and 'str'", 'occurred at index 1')

下面是重现错误的示例:

testx1df = pd.DataFrame()
testx1df['A'] = [100,200,300,400]
testx1df['B'] = [15,60,35,11]
testx1df['C'] = [11,45,22,9]
testx1df['D'] = [5,15,11,3]
testx1df['E'] = [1,6,4,0]


(testx1df[testx1df < 6].apply(lambda x: x.index.get_loc(x.first_valid_index(), method='ffill'), axis=1))

所需的输出应该是具有值 [3,NaN,4,3] 的列表或数组。 NaN 因为它不满足标准。

我检查了 pandas 参考文献,它说对于没有完全匹配的情况,您可以将“方法”更改为 'fill'、'brill' 或 'nearest' 选择上一个、下一个或最接近的索引。基于此,如果我将该方法指定为 'ffill',它将给我一个索引 4 而不是 NaN。但是,当我这样做时它不起作用并且我在问题标题中看到错误显示。对于高于 6 的标准,它可以正常工作,但由于数据框中的第二行不满足它,所以它不会低于 6。

有没有办法解决这个问题?它不应该适用于我的示例(return 之前的索引 3 或 4)吗?

我想到的一个解决方案是添加一个由零填充的虚拟列,这样就有一个地方可以“查找”和满足条件的索引,但这对我来说有点粗糙,我认为还有更多有效的解决方案。

请试试这个:

import numpy as np
ls = list(testx1df[testx1df<6].T.isna().sum())
ls = [np.nan if x==testx1df.shape[1] else x for x in ls]
print(ls)