首页 > 解决方案 > 无法使用 For 循环将数据框的列名附加到列表中

问题描述

我有一个这样的数据框:-

data = [['a', 'b', 'c', 'd'],['q', 'r', 's', 't'],['n'],['w', 'x', 'y', 'z']]
df = pd.DataFrame(data, columns = ['Full_1', 'Full_2', 'Full_3', 'Full_4'])

loop现在我想在函数内部使用 for 附加包含“无”值的数据框的列

lst=[]
def lister(df):
    for c in df.columns:
        if (df[c].isna().max())==True:
            lst.append(c)
            return lst
        else:
            nope = 'None'
            return nope

它返回我“无intseadlst

c现在如果我在for loopie中打印

lst=[]
def lister(df):
    for c in df.columns:
        if (df[c].isna().max())==True:

            print(c)
            #return lst
        else:
            nope = 'None'
            #return nope

c内部for循环的输出:-

Full_2
Full_3
Full_4

那么为什么这些值没有附加到名为 lst 的列表中呢?

预期输出lst:-

['Full_2','Full_3','Full_4']

标签: pythonpandaslistfor-loop

解决方案


>>> df.columns[df.isna().any()].to_list()
['Full_2', 'Full_3', 'Full_4']

编辑:像这样更新你的函数。

def lister(df):
    lst = []
    for c in df.columns:
        if (df[c].isna().max()) == True:
            lst.append(c)
    return lst
>>> lister(df)
['Full_2', 'Full_3', 'Full_4']

推荐阅读