Python:如何删除特定列为空/NaN的行? [英] Python: How to drop a row whose particular column is empty/NaN?

查看:89
本文介绍了Python:如何删除特定列为空/NaN的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个csv文件.我读了:

I have a csv file. I read it:

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的所有行.什么是有效的方法?

I want to remove all the rows where sms column is empty/NaN. What is efficient way to do it?

推荐答案

使用 dropna ,带有参数subset用于指定检查NaN s的列:

Use dropna with parameter subset for specify column for check NaNs:

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 替代:

Alternative with 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

这篇关于Python:如何删除特定列为空/NaN的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆