如果满足其他条件[],如何用[元素]替换系列中的每个元素?

时间:2019-05-23 16:28:10

标签: python pandas lambda list-comprehension series

我试图替换序列中的每个元素而不必在其上循环,如果满足条件,则用'[element]'代替;否则,[],我需要该序列在大多数情况下在每行中包含列表对象有效的方式。

我可以使用for循环/列表理解来完成此操作,这很慢:

    def test_method(A_series, B_series)->pd.Series:
        """return type: pd.Series of lists/ a column of lists"""
        C_series = A_series * B_series/ (1+B_series)
        mask_on = (C_series <= A_series *np.exp(-.25)-B_series)
        updated = [[C_series [i]] if (i in set(C_series [mask_on].index)) else [] for i in C_series.index]
        return pd.Series(updated,C_series.index) 

如果序列如下,并且如果我给出条件i%2 == 0,则序列应变为右侧-

4     2 -> [2]
12    3 -> []
13    4 -> [4]
15    5 -> []

还有另一种方法吗?

1 个答案:

答案 0 :(得分:0)

您可以为此使用Series.where

import numpy as np
import pandas as pd

x = pd.Series(np.arange(10))
x.where(lambda p: p % 2 == 0, np.nan, inplace=True)

print(x)
#0    0.0
#1    NaN
#2    2.0
#3    NaN
#4    4.0
#5    NaN
#6    6.0
#7    NaN
#8    8.0
#9    NaN
#dtype: float64

x = x.apply(lambda p: [p])
print(x)

#0    [0.0]
#1    [NaN]
#2    [2.0]
#3    [NaN]
#4    [4.0]
#5    [NaN]
#6    [6.0]
#7    [NaN]
#8    [8.0]
#9    [NaN]
#dtype: float64