[英]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
它返回我'無' intsead
的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
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.