如何根据上面的行删除行? Python熊猫

时间:2015-10-22 20:25:19

标签: python numpy pandas

我有一个如下所示的数据集:

df = pd.DataFrame({'a': [1,1,1, 2, 3, 3, 4], 'b': [1,np.nan, np.nan, 2, 3, np.nan, 4]})

我希望删除在下一个前一行中具有np.nan的所有行。我无法弄清楚如何执行此操作,因为我不知道如何根据其他行删除行。

3 个答案:

答案 0 :(得分:3)

是的,您可以创建一个掩码,通过合并df.notnulldf.shift来删除不需要的行:

notnull = df.notnull().all(axis=1)
df = df[notnull.shift(-1)]

答案 1 :(得分:3)

您想要查找下一行中包含np.nan的所有行。使用shift:

df.shift().isnull()

       a      b
0   True   True
1  False  False
2  False   True
3  False   True
4  False  False
5  False  False
6  False   True

然后你要弄清楚那行中的任何东西是否为nan,所以你想把它减少到一个布尔掩码。

df.shift().isnull().any(axis=1)

0     True
1    False
2     True
3     True
4    False
5    False
6     True
dtype: bool

然后删除列:

df.drop(df.shift().isnull().any(axis=1))

   a   b
2  1 NaN
3  2   2
4  3   3
5  3 NaN
6  4   4

答案 2 :(得分:2)

使用notnull测试行是否为null:

In [11]: df.notnull()
Out[11]:
      a      b
0  True   True
1  True  False
2  True  False
3  True   True
4  True   True
5  True  False
6  True   True

In [12]: df.notnull().all(1)
Out[12]:
0     True
1    False
2    False
3     True
4     True
5    False
6     True
dtype: bool

In [13]: df[df.notnull().all(1)]
Out[13]:
   a  b
0  1  1
3  2  2
4  3  3
6  4  4

你可以向下移动以获得上面的行是否为NaN:

In [14]: df.notnull().all(1).shift().astype(bool)
Out[14]:
0     True
1     True
2    False
3    False
4     True
5     True
6    False
dtype: bool

In [15]: df[df.notnull().all(1).shift().astype(bool)]
Out[15]:
   a   b
0  1   1
1  1 NaN
4  3   3
5  3 NaN

注意:您可以使用shift(-1)向上移动。