Pandas是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具。Pandas提供了大量能使我们快速便捷地处理数据的函数和方法。你很快就会发现,它是使Python成为强大而高效的数据分析环境的重要因素之一。本文主要介绍一下Pandas中pandas.DataFrame.dropna方法的使用。

DataFrame.dropna(self, axis=0, how='any', thresh=None, subset=None, inplace=False)

删除缺失的值。

请参阅《用户指南》,以了解有关哪些值被认为缺失以及如何处理缺失数据的更多信息。

参数

axis : {0或'index',1或'columns'},默认0

确定是否删除包含缺失值的行或列。

    0或'index':删除包含缺失值的行。

    1或“列”:删除包含缺失值的列。

从0.23.0版开始不推荐使用:将元组或列表传递到多个轴上。只允许一个轴。

how : {'any','all'},默认为'any'

当我们有至少一个NA或全部NA时,确定是否从DataFrame中删除行或列。

    'any':如果存在任何NA值,则删除该行或列。

    'all':如果所有值均为NA,则删除该行或列。

thresh : int,可选

需要许多非NA值。

subset :类数组,可选

要考虑的其他轴上的标签,例如,如果要删除行,这些标签将是要包括的列的列表。

inplace : bool,默认为False

如果为True,则执行就地操作并返回None

返回

DataFrame

删除了NA条目的DataFrame。

例子

>>> df = pd.DataFrame({"name": ['Alfred', 'Batman', 'Catwoman'],
... "toy": [np.nan, 'Batmobile', 'Bullwhip'],
... "born": [pd.NaT, pd.Timestamp("1940-04-25"),
... pd.NaT]})
>>> df
name toy born
0 Alfred NaN NaT
1 Batman Batmobile 1940-04-25
2 Catwoman Bullwhip NaT

将行缺失至少一个元素

>>> df.dropna()
name toy born
1 Batman Batmobile 1940-04-25

将列放在缺少至少一个元素的位置

>>> df.dropna(axis='columns')
name
0 Alfred
1 Batman
2 Catwoman

删除所有元素均缺失的行

>>> df.dropna(how='all')
name toy born
0 Alfred NaN NaT
1 Batman Batmobile 1940-04-25
2 Catwoman Bullwhip NaT

仅保留至少具有2个非NA值的行

>>> df.dropna(thresh=2)
name toy born
1 Batman Batmobile 1940-04-25
2 Catwoman Bullwhip NaT

定义在哪些列中查找缺失值

>>> df.dropna(subset=['name', 'born'])
name toy born
1 Batman Batmobile 1940-04-25

将具有有效条目的DataFrame保留在同一变量中

>>> df.dropna(inplace=True)
>>> df
name toy born
1 Batman Batmobile 1940-04-25


推荐文档

相关文档

大家感兴趣的内容

随机列表