初始化空Pandas系列并有条件地添加到它

时间:2018-02-09 15:45:48

标签: python pandas dataframe

我有一个名为X的pandas DataFrame,如下所示。

X = pd.DataFrame({
    'month_1': [1, 0, 0, 0, 0],
    'month_2': [0, 1, 0, 0, 0],
    'age': [1, 2, 3, 4, 5]
})
months = X['month_1'] + X['month_2']
age = X['age']

我想创建一个方程式,根据来自X的术语是真还是假来汇总来自keep的系列。以下代码有效。

keep={'seasonality':True, 'age':True}

equation = months
if keep['age']:
    equation = equation + age

print(equation)

0    2
1    3
2    3
3    4
4    5
dtype: int64

但是,如果我使用空系列初始化equation,然后根据keep添加字词,则无法使其生效。当我尝试这样做时,我得到了NaN值。我怎么能这样做?

keep={'seasonality':True, 'age':True}

equation = pd.Series([])
if keep['seasonality']:
    equation = equation + months
if keep['age']:
    equation = equation + age

print(equation)

0   NaN
1   NaN
2   NaN
3   NaN
4   NaN
dtype: float64

1 个答案:

答案 0 :(得分:3)

如果我理解正确,您可以使用com.example.app/com.example.app.receiver.AdminReceiver + add

fill_value=0