我有一个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的所有行。什么是有效的方法? 最佳答案
使用带有参数dropna
的 subset
来指定检查NaN
的列:
data = data.dropna(subset=['sms'])
print (data)
id city department sms category
1 2 lhr revenue good 1
boolean indexing
和 notnull
的另一种解决方案:data = data[data['sms'].notnull()]
print (data)
id city department sms category
1 2 lhr revenue good 1
用
query
替代: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