如何计算 Pandas Dataframe 列中的 NaN 出现的次数
我们将介绍在 Pandas DataFrame 的一列中计算 NaN 出现次数的方法。我们有很多选择,包括针对一列或多列的 isna()
方法,通过从 NaN
出现次数中减去总长度,使用 value_counts
方法,以及使用 df.isnull().sum()
方法。
我们还将介绍计算整个 Pandas DataFrame 中 NaN
出现总数的方法。
isna()
方法来计算一列或多列中的 NaN
我们可以使用 insna()
方法(Pandas 版本> 0.21.0),然后求和以计算 NaN
的出现。对于一列,我们将执行以下操作:
import pandas as pd
s = pd.Series([1, 2, 3, np.nan, np.nan])
s.isna().sum()
# or s.isnull().sum() for older pandas versions
输出:
2
对于几列,它也适用:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, np.nan], "b": [np.nan, 1, np.nan]})
df.isna().sum()
输出:
a 1
b 2
dtype: int64
从总长度中减去 non-NaN
的计数以计算 NaN
的出现次数
我们可以通过从 dataframe 的长度中减去非 NaN
出现的次数来获得每一列中 NaN
出现的次数:
import pandas as pd
df = pd.DataFrame(
[(1, 2, None), (None, 4, None), (5, None, 7), (5, None, None)],
columns=["a", "b", "d"],
index=["A", "B", "C", "D"],
)
print(df)
print(len(df) - df.count())
输出:
a b d
A 1.0 2.0 NaN
B NaN 4.0 NaN
C 5.0 NaN 7.0
D 5.0 NaN NaN
a 1
b 2
d 3
dtype: int64
df.isnull().sum()
方法来计算 NaN
的出现次数
我们可以使用 df.isnull().sum()
方法获得每一列中 NaN
出现的次数。如果我们在 sum
方法中传递了 axis=0
,它将给出每列中出现 NaN
的次数。如果需要在每行中出现 NaN
次,我们需要设置 axis=1
。
考虑以下代码:
import pandas as pd
df = pd.DataFrame(
[(1, 2, None), (None, 4, None), (5, None, 7), (5, None, None)],
columns=["a", "b", "d"],
index=["A", "B", "C", "D"],
)
print("NaN occurrences in Columns:")
print(df.isnull().sum(axis=0))
print("NaN occurrences in Rows:")
print(df.isnull().sum(axis=1))
输出:
NaN occurrences in Columns:
a 1
b 2
d 3
dtype: int64
NaN occurrences in Rows:
A 1
B 2
C 1
D 2
dtype: int64
计算整个 Pandas DataFrame 中 NaN
的出现
为了获得在 DataFrame
中所有 NaN
出现的总数,我们将两个 .sum()
方法链接在一起:
import pandas as pd
df = pd.DataFrame(
[(1, 2, None), (None, 4, None), (5, None, 7), (5, None, None)],
columns=["a", "b", "d"],
index=["A", "B", "C", "D"],
)
print("NaN occurrences in DataFrame:")
print(df.isnull().sum().sum())
输出:
NaN occurrences in DataFrame:
6
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串