python - 为什么 pandas df.loc + lambda 不起作用?

标签 python pandas lambda dataframe

我已经从 csv 文件创建了 pandas 框架。 我想使用 lambda 选择行。 但它不起作用。 我用 this pandas manual . enter image description here 异常(exception): enter image description here

有什么问题? 谢谢。

最佳答案

正如@BrenBam 在评论中所说,此语法是在 0.18.1 中添加的,在以前的版本中不起作用。

按可调用方式选择:

.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.

示例(版本 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

对于 <= 0.18.0 的版本,您不能使用Selection by callable:

改为这样做:

df.loc[df['Date'] == '2003-01-01 00:00:00', ['Date']]

关于python - 为什么 pandas df.loc + lambda 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37102824/

相关文章:

python - TensorFlow 1.0.0 的prepare_attention API 相当于tensorflow 1.2.0

python - pandas dataframe 根据列中的值删除后续行

c# - 如何获取生成 lambda 表达式的(源代码)字符串?

c++ - 下标迭代器中的 lambda

python - 在 python 中使用 pydoop 保存 gzip 文件

python - Microsoft 合作伙伴生成 token

python - pandas 计算每月平均值

python - 当同一列具有不同格式时转换 DataFrame 上的日期格式

c# - 按递增顺序将列表拆分为多个列表

python - 这种列表理解的正确 python 语法是什么?