Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize empty Pandas series and conditionally add to it

I have a pandas DataFrame named X as shown below.

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']

I want to create an equation that adds up series from X based on whether that term from keep is True or False. The code below works.

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

However, I can't get it to work if I initialize equation with an empty series and then add terms based on keep. When I try to do this I get NaN values. How can I do this?

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
like image 533
Gaurav Bansal Avatar asked Feb 09 '18 15:02

Gaurav Bansal


1 Answers

If I understand correctly , you can using add + fill_value=0

equation = pd.Series([])
if keep['seasonality']:
    equation = equation.add(months,fill_value=0)
if keep['age']:
    equation = equation.add(age,fill_value=0)
equation
Out[91]: 
0    2.0
1    3.0
2    3.0
3    4.0
4    5.0
dtype: float64
like image 184
BENY Avatar answered Oct 08 '22 01:10

BENY