下一行为数字时获取数据帧

时间:2018-06-05 10:57:25

标签: python pandas

我有一个看起来像这样的DataFrame:

import numpy as np 
import pandas as pd

df=pd.DataFrame([['ph','ro','to'],[5,5,8],[4,3,1],['ph','ro','to'],[np.NaN,np.NaN,np.NaN],
                 [np.NaN,np.NaN,np.NaN],['ph','ro','togr'],[5,5,8],['ph','gho','to'],
                 [np.NaN,np.NaN,np.NaN]],columns=['A','B','C'])

DF

     A    B     C
0   ph   ro    to
1    5    5     8
2    4    3     1
3   ph   ro    to
4  NaN  NaN   NaN
5  NaN  NaN   NaN
6   ph   ro  togr
7    5    5     8
8   ph  gho    to
9  NaN  NaN   NaN

我想要做的是获取df.A='ph'的位置,并且同一列中的下一行是数字并获得:

    A    B     C
0   ph   ro    to
6   ph   ro  togr

2 个答案:

答案 0 :(得分:0)

试试这个,

print df[(df['A']=='ph')&(pd.to_numeric(df.A,errors='coerce').shift(-1).notnull())]

输出:

    A   B     C
0  ph  ro    to
6  ph  ro  togr

答案 1 :(得分:0)

这是一种方式:

In [64]: mask1 = df['A'] == 'ph'

In [65]: mask2 = df['A'].astype(str).str.isdigit()

In [66]: df[:-1].loc[np.logical_and(mask1[:-1], mask2[1:])]
Out[66]: 
    A   B     C
0  ph  ro    to
6  ph  ro  togr