筛选出DataFrame中某一列不为空的行

683 阅读1分钟

有几种方法可以筛选出DataFrame中某一列不为空的行。除了使用notna(),还可以使用dropna()方法或者直接使用布尔索引。以下是几种不同的方法:

方法1:使用notna()

import pandas as pd

# 假设这是你的数据框
data = {
    'A': [1, 2, None, 4],
    'B': [5, None, 6, 7],
    'C': [8, 9, 10, None]
}
df = pd.DataFrame(data)

# 使用notna()方法
non_empty_A = df[df['A'].notna()]

print(non_empty_A)

方法2:使用dropna()

dropna()方法可以直接删除包含NaN值的行。可以指定subset参数只考虑特定列。

# 使用dropna()方法
non_empty_A = df.dropna(subset=['A'])

print(non_empty_A)

方法3:使用布尔索引

可以直接使用布尔条件来筛选出不为空的行。

# 使用布尔索引
non_empty_A = df[df['A'] != None]

print(non_empty_A)

方法4:使用.notnull()

import pandas as pd

# 假设这是你的数据框
data = {
    'A': [1, 2, None, 4],
    'B': [5, None, 6, 7],
    'C': [8, 9, 10, None]
}
df = pd.DataFrame(data)

# 使用notna()方法
non_empty_A = df[df['A'].notnull()]

print(non_empty_A)

方法4:使用query()方法

query()方法可以用字符串表达式来筛选行。

# 使用query()方法
non_empty_A = df.query('A == A')

print(non_empty_A)

这些方法都可以有效地筛选出DataFrame中某一列不为空的行