Python 初始化空的 Pandas 系列并有条件地添加到其中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48709404/
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-08-19 18:49:14  来源:igfitidea点击:

Initialize empty Pandas series and conditionally add to it

pythonpandasdataframe

提问by Gaurav Bansal

I have a pandas DataFrame named Xas shown below.

我有一个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']

I want to create an equation that adds up series from Xbased on whether that term from keepis True or False. The code below works.

我想创建一个方程式,X根据该术语keep是 True 还是 False ,将系列相加。下面的代码有效。

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 equationwith 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?

但是,如果我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

回答by YOBEN_S

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

如果我理解正确,您可以使用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