I have a Dataframe like this:-
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
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
Now If I print c
Inside of for loop
ie
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:-
Full_2
Full_3
Full_4
So Why these values not appending in list named lst?
Expected output of lst
:-
['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.
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.
Move your lst=[]
line outside of the for loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.