Python:如何删除特定列为空/ NaN的行?

时间:2017-09-07 08:49:35

标签: python pandas dataframe

我有一个csv文件。我读了它:

import pandas as pd
data = pd.read_csv('my_data.csv', sep=',')
data.head()

输出如:

id    city    department    sms    category
01    khi      revenue      NaN       0
02    lhr      revenue      good      1
03    lhr      revenue      NaN       0

我想删除sms列为空/ NaN的所有行。什么是有效的方法呢?

2 个答案:

答案 0 :(得分:14)

使用带有参数subset的{​​{3}}来指定检查NaN的列:

data = data.dropna(subset=['sms'])
print (data)
   id city department   sms  category
1   2  lhr    revenue  good         1

dropnaboolean indexing的另一种解决方案:

data = data[data['sms'].notnull()]
print (data)
   id city department   sms  category
1   2  lhr    revenue  good         1

替代notnull

print (data.query("sms == sms"))
   id city department   sms  category
1   2  lhr    revenue  good         1

<强>计时

#[300000 rows x 5 columns]
data = pd.concat([data]*100000).reset_index(drop=True)

In [123]: %timeit (data.dropna(subset=['sms']))
100 loops, best of 3: 19.5 ms per loop

In [124]: %timeit (data[data['sms'].notnull()])
100 loops, best of 3: 13.8 ms per loop

In [125]: %timeit (data.query("sms == sms"))
10 loops, best of 3: 23.6 ms per loop

答案 1 :(得分:1)

您可以使用dropna方法:

data.dropna(axis=0, subset=('sms', ))

有关参数的更多详细信息,请参阅documentation

当然,有多种方法可以做到这一点,并且存在一些轻微的性能差异。除非性能至关重要,否则我更倾向于使用dropna(),因为它是最具表现力的。

import pandas as pd
import numpy as np

i = 10000000

# generate dataframe with a few columns
df = pd.DataFrame(dict(
    a_number=np.random.randint(0,1e6,size=i),
    with_nans=np.random.choice([np.nan, 'good', 'bad', 'ok'], size=i),
    letter=np.random.choice(list('abcdefghijklmnop'), size=i))
                 )

# using notebook %%timeit
a = df.dropna(subset=['with_nans'])
#1.29 s ± 112 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

# using notebook %%timeit
b = df[~df.with_nans.isnull()]
#890 ms ± 59.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

# using notebook %%timeit
c = df.query('with_nans == with_nans')
#1.71 s ± 100 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)