首页 > 解决方案 > 为什么 Panda 的 df.apply 在按原样返回行时比预期的多调用一次?

问题描述

我观察到 Panda 的数据框的 apply 函数有一些奇怪的行为。


test_df = pd.DataFrame(data={
    'A': [1,2,3], 
    'B': [4,5,6],
    'C': [7,8,9]
})
def test(row):
  print('Called Test1')
  return row     # returning row here

def test2(row):
  print('Called Test2')
  return True    # return anything except row

# sample_df = test_df.sample(3, random_state=2)
test_df.apply(test, axis=1)
print('=====================')
test_df.apply(test2, axis=1)
print('Why Test 1 is called 1 time more than test 2.')

输出结果

Called Test1
Called Test1
Called Test1
Called Test1
=====================
Called Test2
Called Test2
Called Test2

问题

  1. 为什么 apply 函数调用test()次数多于 1 次test2()?这是预期的行为吗?

谷歌 Colab 链接:这里

标签: pythonpandasdataframe

解决方案


推荐阅读