Python:在 Pandas 系列上使用 lambda 函数,如果……否则

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28195028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:53:21  来源:igfitidea点击:

Python: using lambda function on Pandas Series, if.. else

pythonif-statementpandaslambdatime-series

提问by Quantatia

I am trying to apply a filter on a series of values stored in a pandas series object. The desired output is the value itself if it meets the criterion otherwise zero. I can only get it to half work:

我正在尝试对存储在 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

where:

在哪里:

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

but the following gives me quite a different result. Clearly I am not understanding what is happening in the background to produce this result:

但以下给了我完全不同的结果。显然,我不明白在后台发生了什么来产生这个结果:

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

results in:

结果是:

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

I am looking for same formatting as the first output except with zeros for where the conditions are not met. Please help.

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

回答by eumiro

Your

您的

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

already returns what you want.

已经返回你想要的。