first question here so it might be a little bit messy.
So I have a data frame like this:
A B
1: 'a' 'aa'
2: 'b' NaN
3: 'c' NaN
4: 'd' 'dd'
And I have a list already created:
lst=[]
I want to append the value in column A
to this list
if the value of Column B
is NaN
, aka to get ['b','c']
in this case.
Loops definitely work but is there an elegant way (by using lambdas, for example) to do so?
Thanks!
Use boolean indexing
for filtering and str.strip
for remove '
:
lst = df.loc[df['B'].isnull(), 'A'].tolist()
print (lst)
["'b'", "'c'"]
lst = df.loc[df['B'].isnull(), 'A'].str.strip("'").tolist()
print (lst)
['b', 'c']
Detail:
print (df['B'].isnull())
1: False
2: True
3: True
4: False
Name: B, dtype: bool
print (df.loc[df['B'].isnull(), 'A'])
2: 'b'
3: 'c'
Name: A, dtype: object
print (df.loc[df['B'].isnull(), 'A'].str.strip("'"))
2: b
3: c
Name: A, dtype: object
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.