[英]Can't append Column Names of Dataframe To A List Using For Loop
I have a Dataframe like this:-我有一个像这样的 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'])
Now I want to append the columns of a dataframe which contains 'None' value using for loop
inside a function现在我想 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
It returns me 'None' intsead
of lst
它返回我'无'
intsead
的lst
Now If I print c
Inside of for loop
ie现在,如果我在
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 of c
inside for
loop:- Output 的
c
内部for
循环:-
Full_2
Full_3
Full_4
So Why these values not appending in list named lst?那么为什么这些值没有附加到名为 lst 的列表中呢?
Expected output of lst
:- lst
的预期 output :-
['Full_2','Full_3','Full_4']
>>> df.columns[df.isna().any()].to_list()
['Full_2', 'Full_3', 'Full_4']
Edit : update your function like this.编辑:像这样更新你的 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']
You're initialising the list every time.您每次都在初始化列表。
So it resets to an empty list inside the if statement.所以它在 if 语句中重置为一个空列表。
Move your lst=[]
line outside of the for loop.将
lst=[]
行移到 for 循环之外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.