Python:在 Pandas Series 上使用 lambda 函数,if..else

标签 python if-statement pandas lambda time-series

我正在尝试对存储在 pandas 系列对象中的一系列值应用过滤器。如果满足标准,则期望的输出是值本身,否则为零。我只能完成一半的工作:

criterion = testdata.map(lambda x: x < 30 or x > 60) 
testdata[criterion] =
Date
2015-01-05    62.358615
2015-01-06    64.349507
2015-01-13    61.726110
2015-01-14    63.574864
2015-01-15    66.020421
2015-01-16    63.041819
2015-01-20    61.458298
Name: rsi, dtype: float64

哪里:

testdata =
Date
2014-12-29    45.821073
2014-12-30    48.946830
2014-12-31    57.737593
2015-01-02    55.424047
2015-01-05    62.358615
2015-01-06    64.349507
2015-01-07    59.452935
2015-01-08    51.182115
2015-01-09    55.044419
2015-01-12    59.365017
2015-01-13    61.726110
2015-01-14    63.574864
2015-01-15    66.020421
2015-01-16    63.041819
2015-01-20    61.458298
2015-01-21    54.432635
2015-01-22    46.985675
2015-01-23    49.740981
2015-01-26    45.102370
2015-01-27    49.800855
Name: rsi, dtype: float64

但下面给出了完全不同的结果。显然,我不了解产生此结果的背景情况:

criterion2 = testdata.map(lambda x: x if (x < 30 or x > 60) else 0) 
testdata[criterion2]

结果:

rsi
0.000000    NaN
0.000000    NaN
0.000000    NaN
0.000000    NaN
62.358615   NaN
64.349507   NaN
0.000000    NaN
0.000000    NaN
0.000000    NaN
0.000000    NaN
61.726110   NaN
63.574864   NaN
66.020421   NaN
63.041819   NaN
61.458298   NaN
0.000000    NaN
0.000000    NaN
0.000000    NaN
0.000000    NaN
0.000000    NaN
Name: rsi, dtype: float64

我正在寻找与第一个输出相同的格式,除了在不满足条件的地方使用零。请帮忙。

最佳答案

你的

testdata.map(lambda x: x if (x < 30 or x > 60) else 0)

已经返回你想要的。

关于Python:在 Pandas Series 上使用 lambda 函数,if..else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28195028/

相关文章:

python - Python 中的 MySQL 动态查询

python - bzrlib 版本与 OSX 上的 bzr 程序不匹配

javascript - 如何在jquery代码中集成 "if"

android - 如何根据 if 条件为 AutocompleteTextview 设置两个适配器

Java闰年检查程序。对边缘值无响应

python - Pandas 应用使用最小/最大在可变滚动窗口上执行缓慢

python - Pandas Dataframe 复杂计算

具有无效语法的 Python while 循环

python - 如何使用 Django Python 显示我最近的 3 篇文章

python - Pandas groupby + scikit learn 电源变压器