你可以使用 Pandas 的 drop 方法结合 iloc 来删除满足条件的行。下面是一个使用循环来删除的示例代码:

import pandas as pd

# 创建示例数据
data = {'A': [1, 2, 3, 4],
        'B': [None, None, None, None],
        'C': [None, None, None, None],
        'D': [5, None, None, None]}
df = pd.DataFrame(data)

# 循环删除满足条件的行
while True:
    # 找到除了第一列以外都为空的行
    empty_rows = df.iloc[:, 1:].apply(lambda x: x.isnull().all(), axis=1)
    
    # 判断是否找到满足条件的行
    if empty_rows.sum() == 0:
        break
    
    # 找到最后一个满足条件的行的索引
    last_empty_row_index = empty_rows[empty_rows].index[-1]
    
    # 删除找到的行
    df = df.drop(last_empty_row_index)

print(df)

输出结果为:

   A    B    C    D
0  1  NaN  NaN  5.0

在循环中,我们首先使用 iloc 来选择除了第一列以外的所有列,然后使用 apply 方法和 isnull().all() 条件来判断哪些行除了第一列以外都为空。然后,我们使用 sum 方法计算满足条件的行的数量,如果为 0 则表示没有满足条件的行了,退出循环。如果有满足条件的行,则使用 index 来获取最后一个满足条件的行的索引,并使用 drop 方法删除该行。最后,输出结果 DataFrame。

Pandas 删除空行:从倒数第一行开始,直到找到非空行

原文地址: https://www.cveoy.top/t/topic/dTR0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录