簡體   English   中英

無法使用 For 循環將 append 的 Dataframe 的列名添加到列表中

[英]Can't append Column Names of Dataframe To A List Using For Loop

我有一個像這樣的 Dataframe:-

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'])

現在我想 append dataframe 的列,其中包含在 function 內使用 for 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

它返回我'無' intseadlst

現在,如果我在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

Output 的c內部for循環:-

Full_2
Full_3
Full_4

那么為什么這些值沒有附加到名為 lst 的列表中呢?

lst的預期 output :-

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

編輯:像這樣更新你的 function 。

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']

您每次都在初始化列表。

所以它在 if 語句中重置為一個空列表。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM