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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With