【问题标题】:Append an entry of dataframe to a list, if the entry of another column is nan in pandas?如果熊猫中另一列的条目是nan,则将数据框的条目附加到列表中?
【发布时间】:2017-10-13 13:25:05
【问题描述】:

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

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

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

我已经创建了一个列表:

lst=[]

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

循环确实有效,但是否有一种优雅的方式(例如,通过使用 lambdas)来做到这一点?

谢谢!

【问题讨论】:

    标签: python pandas lambda list-comprehension


    【解决方案1】:

    使用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
    

    【讨论】:

      猜你喜欢
      • 2019-05-14
      • 1970-01-01
      • 2020-05-21
      • 1970-01-01
      • 2019-08-12
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 2020-09-23
      相关资源
      最近更新 更多