df.iloc[0:1,:].apply(func, axis=1, x,y,z) 执行 func() 2次

df.iloc[0:1,:].apply(func, axis=1, x,y,z) executes func() 2 times

我有一个包含数千行的数据框 df。

对于我要应用函数 func 的每一行。

作为测试,我想 运行 func 仅针对 df 的第一行。在 func() 中,我放置了一个打印语句。我意识到打印语句是 运行 2 次,即使我将 df 切成一行(列还有一个额外的行,但那些是列)。

当我执行以下操作时

df[0:1].apply(func, axis=1, x,y,z)

df.iloc[0:1,:].apply(func, axis=1, x,y,z)

打印语句运行2次,也就是说func()执行了两次

知道为什么会这样吗?

doc 明确表示:

In the current implementation apply calls func twice on the first column/row to decide whether it can take a fast or slow code path.

注意不同的切片技术:

In [134]: df
Out[134]:
   a  b  c
0  9  5  4
1  4  7  2
2  1  3  7
3  6  3  2
4  4  5  2

In [135]: df.iloc[0:1]
Out[135]:
   a  b  c
0  9  5  4

In [136]: df.loc[0:1]
Out[136]:
   a  b  c
0  9  5  4
1  4  7  2

打印:

打印一行作为系列:

In [139]: df[0:1].apply(lambda r: print(r), axis=1)
a    9
b    5
c    4
Name: 0, dtype: int32
Out[139]:
0    None
dtype: object

或使用iloc:

In [144]: df.iloc[0:1, :].apply(lambda r: print(r), axis=1)
a    9
b    5
c    4
Name: 0, dtype: int32
Out[144]:
0    None
dtype: object

打印两个rows/Series:

In [140]: df.loc[0:1].apply(lambda r: print(r), axis=1)
a    9
b    5
c    4
Name: 0, dtype: int32
a    4
b    7
c    2
Name: 1, dtype: int32
Out[140]:
0    None
1    None
dtype: object

OP:

"the print statement was run 2 times even though I am slicing df to one row"

实际上,您将其切成两行