Python 熊猫列加法/减法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14102195/
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
Pandas column addition/subtraction
提问by user1911092
I am using a pandas/python dataframe. I am trying to do a lag subtraction.
我正在使用 Pandas/python 数据框。我正在尝试进行滞后减法。
I am currently using:
我目前正在使用:
newCol = df.col - df.col.shift()
This leads to a NaN in the first spot:
这导致第一个位置为 NaN:
NaN
45
63
23
...
First question: Is this the best way to do a subtraction like this?
第一个问题:这是做这样的减法的最好方法吗?
Second: If I want to add a column (same number of rows) to this new column. Is there a way that I can make all the NaN's 0's for the calculation?
第二:如果我想向这个新列添加一列(相同数量的行)。有没有办法让所有的 NaN 都为 0 来计算?
Ex:
前任:
col_1 =
Nan
45
63
23
col_2 =
10
10
10
10
new_col =
10
55
73
33
and NOT
并不是
NaN
55
73
33
Thank you.
谢谢你。
采纳答案by unutbu
I think your method of of computing lags is just fine:
我认为您计算滞后的方法很好:
import pandas as pd
df = pd.DataFrame(range(4), columns = ['col'])
print(df['col'] - df['col'].shift())
# 0 NaN
# 1 1
# 2 1
# 3 1
# Name: col
print(df['col'] + df['col'].shift())
# 0 NaN
# 1 1
# 2 3
# 3 5
# Name: col
If you wish NaNplus (or minus) a number to be the number (not NaN), use the add(or sub) method with fill_value = 0:
如果您希望NaN加上(或减去)一个数字作为数字(不是NaN),请使用add(or sub) 方法fill_value = 0:
print(df['col'].sub(df['col'].shift(), fill_value = 0))
# 0 0
# 1 1
# 2 1
# 3 1
# Name: col
print(df['col'].add(df['col'].shift(), fill_value = 0))
# 0 0
# 1 1
# 2 3
# 3 5
# Name: col

