繁体   English   中英

如果另一列的条目在pandas中是nan,则将数据框的条目追加到列表中?

[英]Append an entry of dataframe to a list, if the entry of another column is nan in pandas?

这里的第一个问题,所以可能有点混乱。

所以我有一个像这样的数据框:

           A          B
1:        'a'       'aa'
2:        'b'       NaN
3:        'c'       NaN
4:        'd'       'dd'

我已经创建了一个列表:

lst=[]

如果Column B值为NaN ,我想将column A的值附加到此list ['b','c']在这种情况下,也就是['b','c']

循环肯定有效,但是是否有一种优雅的方法(例如,使用lambda)呢?

谢谢!

使用boolean indexing进行过滤,使用str.strip除去'

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

详情:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM