Why does not work pandas df.loc + lambda?

2019-07-29 17:08发布

I have created pandas frame from csv file. And I want to select rows use lambda. But it does not work. I use this pandas manual. enter image description here exception: enter image description here

what is problem? thanks.

1条回答
Bombasti
2楼-- · 2019-07-29 17:46

As @BrenBam has said in the comment this syntax was added in 0.18.1 and it won't work in previous versions.

Selection By Callable:

.loc, .iloc, .ix and also [] indexing can accept a callable as indexer. The callable must be a function with one argument (the calling Series, DataFrame or Panel) and that returns valid output for indexing.

Example (version 0.18.1):

In [10]: df
Out[10]:
   a  b  c
0  1  4  2
1  2  2  4
2  3  4  0
3  0  2  3
4  3  0  4

In [11]: df.loc[lambda df: df.a == 3]
Out[11]:
   a  b  c
2  3  4  0
4  3  0  4

For versions <= 0.18.0 you can't use Selection by callable:

do it this way instead:

df.loc[df['Date'] == '2003-01-01 00:00:00', ['Date']]
查看更多
登录 后发表回答