Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何删除某列中值为NaN的数据帧行_Python_Pandas_Dataframe_Nan - Fatal编程技术网

Python 如何删除某列中值为NaN的数据帧行

Python 如何删除某列中值为NaN的数据帧行,python,pandas,dataframe,nan,Python,Pandas,Dataframe,Nan,我有这个DataFrame,只想要EPS列不是NaN的记录: >>> df STK_ID EPS cash STK_ID RPT_Date 601166 20111231 601166 NaN NaN 600036 20111231 600036 NaN 12 600016 20111231 600016 4.3 NaN 601009 20111231 601009 NaN

我有这个
DataFrame
,只想要
EPS
列不是
NaN
的记录:

>>> df
                 STK_ID  EPS  cash
STK_ID RPT_Date                   
601166 20111231  601166  NaN   NaN
600036 20111231  600036  NaN    12
600016 20111231  600016  4.3   NaN
601009 20111231  601009  NaN   NaN
601939 20111231  601939  2.5   NaN
000001 20111231  000001  NaN   NaN
…即。类似于
df.drop(..)
的方法来获得这个结果数据帧:

                  STK_ID  EPS  cash
STK_ID RPT_Date                   
600016 20111231  600016  4.3   NaN
601939 20111231  601939  2.5   NaN

我该怎么做呢?

不要放弃,只选择EPS不是NA的行:

df=df[df['EPS'].notna()]

这个问题已经解决了,但是

…也考虑Wouter提出的解决方案。处理缺失数据(包括

dropna()
)的功能内置于pandas中。除了与手动操作相比可能提高的性能外,这些功能还提供了各种可能有用的选项

In [24]: df = pd.DataFrame(np.random.randn(10,3))

In [25]: df.iloc[::2,0] = np.nan; df.iloc[::4,1] = np.nan; df.iloc[::3,2] = np.nan;

In [26]: df
Out[26]:
          0         1         2
0       NaN       NaN       NaN
1  2.677677 -1.466923 -0.750366
2       NaN  0.798002 -0.906038
3  0.672201  0.964789       NaN
4       NaN       NaN  0.050742
5 -1.250970  0.030561 -2.678622
6       NaN  1.036043       NaN
7  0.049896 -0.308003  0.823295
8       NaN       NaN  0.637482
9 -0.310130  0.078891       NaN




还有其他选项(请参见中的文档),包括删除列而不是行


非常方便

我知道这一点已经得到了回答,但这仅仅是为了解决这个具体问题,而不是为了Aman的一般描述(这太棒了),如果有其他人发生这种情况:

import pandas as pd
df = df[pd.notnull(df['EPS'])]

您可以使用数据帧方法或的逆,或:


可在以下位置添加“&”,可用于添加附加条件,例如

df = df[(df.EPS > 2.0) & (df.EPS <4.0)]

df=df[(df.EPS>2.0)和(df.EPS另一个解决方案使用了
np.nan!=np.nan
这一事实:

In [149]: df.query("EPS == EPS")
Out[149]:
                 STK_ID  EPS  cash
STK_ID RPT_Date
600016 20111231  600016  4.3   NaN
601939 20111231  601939  2.5   NaN
您可以使用以下选项:

df.dropna(subset=['EPS'], how='all', inplace=True)

最简单的解决方案:

filtered_df = df[df['EPS'].notnull()]
上述解决方案比使用np.isfinite()要好得多


简单易行的方法

df.dropna(子集=['EPS'],inplace=True)


来源:

在有大量列的数据集中,最好能看到有多少列包含空值,有多少列不包含空值

print("No. of columns containing null values")
print(len(df.columns[df.isna().any()]))

print("No. of columns not containing null values")
print(len(df.columns[df.notna().all()]))

print("Total no. of columns in the dataframe")
print(len(df.columns))
例如,在我的dataframe中,它包含82列,其中19列至少包含一个空值

此外,您还可以自动删除列和行,具体取决于哪个列具有更多的空值
以下是智能执行此操作的代码:

df = df.drop(df.columns[df.isna().sum()>len(df.columns)],axis = 1)
df = df.dropna(axis = 0).reset_index(drop=True)
注意:上述代码将删除所有空值。如果需要空值,请在之前处理它们。

其他版本:

df[~df['EPS'].isna()]
如何删除某列中值为NaN的数据帧行 这是一个被殴打致死的老问题,但我相信这条线索上会有一些更有用的信息。如果你想找到以下问题的答案,请继续阅读:

  • 如果它的任何值都是NaN,我可以删除行吗?如果它们都是NaN呢
  • 在删除行时,我可以只查看特定列中的NaN吗
  • 我可以删除具有特定NaN值计数的行吗
  • 如何删除列而不是行
  • 我尝试了上面的所有选项,但我的数据帧无法更新

:用法和示例 已经有人说过,
df.dropna
是从数据帧中删除NAN的标准方法,但是在这一过程中没有什么比一些视觉提示更有用的了

# Setup
df = pd.DataFrame({
    'A': [np.nan, 2, 3, 4],  
    'B': [np.nan, np.nan, 2, 3], 
    'C': [np.nan]*3 + [3]}) 

df                      
     A    B    C
0  NaN  NaN  NaN
1  2.0  NaN  NaN
2  3.0  2.0  NaN
3  4.0  3.0  3.0
以下是最重要的参数及其工作原理的详细信息,以常见问题解答的形式排列


如果它的任何值都是NaN,我可以删除行吗?如果它们都是NaN呢? 这就是
how=…
参数派上用场的地方

  • 'any'
    (默认)-如果至少有一列具有NaN,则删除行
  • 'all'
    -仅当其所有列都有NAN时才删除行

注意
如果您只想查看哪些行是空的(如果您想要 行的布尔掩码),使用 :

要获得此结果的反演,请使用 相反


在删除行时,我可以只查看特定列中的NaN吗? 这是
subset=[…]
参数的一个用例

指定列(或轴为1的索引)列表,以便在删除行(或轴为1的列)时仅查看这些列(或轴为1的行)

# Drop all rows with NaNs in A
df.dropna(subset=['A'])

     A    B    C
1  2.0  NaN  NaN
2  3.0  2.0  NaN
3  4.0  3.0  3.0

# Drop all rows with NaNs in A OR B
df.dropna(subset=['A', 'B'])

     A    B    C
2  3.0  2.0  NaN
3  4.0  3.0  3.0
df.dropna()

     A    B    C
3  4.0  3.0  3.0

# All columns have rows, so the result is empty.
df.dropna(axis=1)

Empty DataFrame
Columns: []
Index: [0, 1, 2, 3]

# Here's a different example requiring the column to have all NaN rows
# to be dropped. In this case no columns satisfy the condition.
df.dropna(axis=1, how='all')

     A    B    C
0  NaN  NaN  NaN
1  2.0  NaN  NaN
2  3.0  2.0  NaN
3  4.0  3.0  3.0

# Here's a different example requiring a column to have at least 2 NON-NULL
# values. Column C has less than 2 NON-NULL values, so it should be dropped.
df.dropna(axis=1, thresh=2)

     A    B
0  NaN  NaN
1  2.0  NaN
2  3.0  2.0
3  4.0  3.0

我可以删除具有特定NaN值计数的行吗? 这是
thresh=…
参数的一个用例。请将非空值的最小数目指定为整数

df.dropna(thresh=1)  

     A    B    C
1  2.0  NaN  NaN
2  3.0  2.0  NaN
3  4.0  3.0  3.0

df.dropna(thresh=2)

     A    B    C
2  3.0  2.0  NaN
3  4.0  3.0  3.0

df.dropna(thresh=3)

     A    B    C
3  4.0  3.0  3.0
这里需要注意的是,您需要指定要保留多少非空值,而不是要删除多少空值。这是新用户的痛点

幸运的是,修复很容易:如果有空值计数,只需从列大小中减去它即可获得函数的正确thresh参数

required_min_null_values_to_drop = 2 # drop rows with at least 2 NaN
df.dropna(thresh=df.shape[1] - required_min_null_values_to_drop + 1)

     A    B    C
2  3.0  2.0  NaN
3  4.0  3.0  3.0

如何删除列而不是行? 使用
axis=…
参数,它可以是
axis=0
axis=1

# Drop all rows with NaNs in A
df.dropna(subset=['A'])

     A    B    C
1  2.0  NaN  NaN
2  3.0  2.0  NaN
3  4.0  3.0  3.0

# Drop all rows with NaNs in A OR B
df.dropna(subset=['A', 'B'])

     A    B    C
2  3.0  2.0  NaN
3  4.0  3.0  3.0
df.dropna()

     A    B    C
3  4.0  3.0  3.0

# All columns have rows, so the result is empty.
df.dropna(axis=1)

Empty DataFrame
Columns: []
Index: [0, 1, 2, 3]

# Here's a different example requiring the column to have all NaN rows
# to be dropped. In this case no columns satisfy the condition.
df.dropna(axis=1, how='all')

     A    B    C
0  NaN  NaN  NaN
1  2.0  NaN  NaN
2  3.0  2.0  NaN
3  4.0  3.0  3.0

# Here's a different example requiring a column to have at least 2 NON-NULL
# values. Column C has less than 2 NON-NULL values, so it should be dropped.
df.dropna(axis=1, thresh=2)

     A    B
0  NaN  NaN
1  2.0  NaN
2  3.0  2.0
3  4.0  3.0
告诉函数是要删除行(
axis=0
)还是要删除列(
axis=1


我尝试了上面的所有选项,但我的数据帧无法更新!
dropna
,与pandas API中的大多数其他函数一样,返回一个新的数据帧(带有更改的原始数据帧的副本),因此如果希望看到更改,应将其重新分配

df.dropna(...) # wrong
df.dropna(..., inplace=True) # right, but not recommended
df = df.dropna(...) # right

参考文献


dropna:
df.dropna(子集=['column1\u name'、'column2\u name'、'column3\u name']
我建议使用
pandas.notnull
而不是
np.isfinite
索引和复制比删除有什么好处吗?创建错误:类型错误:输入类型不支持ufunc'isfinite',并且根据强制转换规则“safe”,无法将输入安全强制为任何支持的类型@wes mckinney c请告诉我,在这种情况下,dropna()是否比pandas.notnull更好?如果是,那么为什么?@PhilippSchwarz如果列(
EPS
在示例中)包含无法被
np.isfinite()
消化的字符串或其他类型,则会发生此错误。我建议使用
pandas.notnull()
这将处理更多的问题
# Drop all rows with NaNs in A
df.dropna(subset=['A'])

     A    B    C
1  2.0  NaN  NaN
2  3.0  2.0  NaN
3  4.0  3.0  3.0

# Drop all rows with NaNs in A OR B
df.dropna(subset=['A', 'B'])

     A    B    C
2  3.0  2.0  NaN
3  4.0  3.0  3.0
df.dropna(thresh=1)  

     A    B    C
1  2.0  NaN  NaN
2  3.0  2.0  NaN
3  4.0  3.0  3.0

df.dropna(thresh=2)

     A    B    C
2  3.0  2.0  NaN
3  4.0  3.0  3.0

df.dropna(thresh=3)

     A    B    C
3  4.0  3.0  3.0
required_min_null_values_to_drop = 2 # drop rows with at least 2 NaN
df.dropna(thresh=df.shape[1] - required_min_null_values_to_drop + 1)

     A    B    C
2  3.0  2.0  NaN
3  4.0  3.0  3.0
df.dropna()

     A    B    C
3  4.0  3.0  3.0

# All columns have rows, so the result is empty.
df.dropna(axis=1)

Empty DataFrame
Columns: []
Index: [0, 1, 2, 3]

# Here's a different example requiring the column to have all NaN rows
# to be dropped. In this case no columns satisfy the condition.
df.dropna(axis=1, how='all')

     A    B    C
0  NaN  NaN  NaN
1  2.0  NaN  NaN
2  3.0  2.0  NaN
3  4.0  3.0  3.0

# Here's a different example requiring a column to have at least 2 NON-NULL
# values. Column C has less than 2 NON-NULL values, so it should be dropped.
df.dropna(axis=1, thresh=2)

     A    B
0  NaN  NaN
1  2.0  NaN
2  3.0  2.0
3  4.0  3.0
df.dropna(...) # wrong
df.dropna(..., inplace=True) # right, but not recommended
df = df.dropna(...) # right
DataFrame.dropna(
    self, axis=0, how='any', thresh=None, subset=None, inplace=False)