首页 > 解决方案 > 测试无类型的熊猫数据框

问题描述

pytest用来测试我的代码。

我想执行的一个特定测试是关于在 pandas 中的列上运行的函数df

一个函数foo_fun应用于pandas df,它会在对原始数据帧执行一些操作后添加一个新列。如果输入是这个函数None应该返回None

例子:

def foo_fun(data):
   # create a new column based on INFO column
   txt=list(data.INFO)
   data['NEW_COLUMN'] = ['value' if s is not None else None for s in txt]
   return data

def foo_test():
    fake_data = pd.DataFrame({'ENTITYKEY':['1','2','3','4'],
                              'INFO':['That\'s what she said',
                                      'Questo è un testo in italiano',
                                      'Eso es lo que dice el',
                                      None]})

   fake_data  = foo_fun(fake_data)
   assert(all(fake_data['NEW_COLUMN']==['value','value','value',None]))

我该如何测试呢?测试失败,问题是最后一个值,None.

标签: pythonpandasunit-testingdataframe

解决方案


使用 iloc 获取最后一列,然后检查。

if fake_data.iloc[:,-1] != None:
  print("Last Column is not None")

推荐阅读