获取以模式开头的字符串的单元格的所有行和列位置

2024-03-29 14:15:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框,我想知道以Nr.开头的字符串单元格的位置(行和列索引):

df = pd.DataFrame({'A':['Nr.Example1',2,'CAT'],
                'B':[3,'Nr.Example2','Nr. Example3'],
                'C':[4,'Nr. example 4','DOG']})

考虑到,基于上述数据帧,感兴趣的行和列将是:

'Nr.Example1' = (0, 'A') or (0, 0)
'Nr.Example2' = (1, 'B') or (1, 1)
'Nr. Example3' = (2, 'B') or (2, 1)
'Nr. example 4' = (1, 'C') or (1, 2)

我想要一个像这样的输出:

locs = [(0, 'A'),(1, 'B'),(2, 'B'),(1, 'C')]
or
ilocs = [(0, 0),(1, 1),(2, 1),(1, 2)]

我可以用

locs = df[df == 'Nr.Example1'].stack().index.tolist()

ilocs = np.where(df.values == 'Nr.Example1')

在每一种可能性上循环运行这些代码行,并将结果附加到列表中。然而,我并不预先知道所有的可能性。我知道它总是以Nr.开头


Tags: or数据字符串dataframedfexample可能性nr
2条回答

通过np.where

index = (np.where(df.astype(str).applymap(lambda x: x.startswith('Nr.')).values ==  True))
result = list(zip(index[0],index[1]))

输出:

[(0, 0), (1, 1), (1, 2), (2, 1)]

您可以stack数据帧,并查找所有str.startswith'Nr.'的记录的索引:

df.stack().str.startswith('Nr.')[lambda x: x==True].index.tolist()

输出:

[(0, 'A'), (1, 'B'), (1, 'C'), (2, 'B')]

或与numpy一起:

np.argwhere(np.char.startswith(df.values.astype(str), 'Nr.'))

输出:

array([[0, 0],
       [1, 1],
       [1, 2],
       [2, 1]])

相关问题 更多 >