【问题标题】:Can't append Column Names of Dataframe To A List Using For Loop无法使用 For 循环将数据框的列名附加到列表中
【发布时间】:2021-05-29 03:46:42
【问题描述】:

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

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 附加包含“无”值的数据框的列

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

它返回“无”intsead of lst

现在如果我在for loop 的内部打印c,即

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

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

cfor 循环内的输出:-

Full_2
Full_3
Full_4

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

lst的预期输出:-

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

【问题讨论】:

    标签: python pandas list for-loop


    【解决方案1】:
    >>> 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']
    

    【讨论】:

    • 嘿!我只是稍微改变一下问题...看看
    • 你真的要使用循环吗?
    • 是的,我想使用 for 循环,这就是我遇到问题的原因
    • else 部分呢?@Corralien
    • 你想用else 部分做什么。如果您对变量 nope 不做任何事情,nope = None 将毫无用处。
    【解决方案2】:

    您每次都在初始化列表。

    所以它在 if 语句中重置为一个空列表。

    lst=[] 行移到 for 循环之外。

    【讨论】:

    • 嘿!我只是稍微改变一下问题...看看...顺便说一句你的解决方案不起作用
    猜你喜欢
    • 2018-07-20
    • 2021-03-15
    • 1970-01-01
    • 2020-04-25
    • 2020-07-26
    • 2019-04-11
    • 1970-01-01
    • 2020-09-25
    • 2017-03-22
    相关资源
    最近更新 更多