[英]How do I calculate colums in pandas dataframe?
I basically want to type a formula and apply it on the rest below.我基本上想键入一个公式并将其应用于下面的 rest。 My problem is that I don't know how to tell pandas that it has to pick two items out of the same column and for every new calculation, it has to "move down" the cell selection.
我的问题是我不知道如何告诉 pandas 它必须从同一列中选择两个项目,并且对于每个新计算,它必须“向下移动”单元格选择。
Using shift function will give you get the result you are looking for:使用shift function 会给你你正在寻找的结果:
# Assuming your dataframe it's called df and the columns are 'A' and 'B'
df["B"] = (df["A"] + df["A"].shift(-1))*df["A"].shift(-1)
Panda's shift function moves every row (up or down) the number of positions considering the number given as a parameter.熊猫的移位function 考虑作为参数给出的数字,每行(向上或向下)移动位置数。
If you move every row -1 position, you'll get a dataframe which has every row moved one position up (making the first row to disappear and the last one filled with NaN ).如果你移动每一行 -1 position,你会得到一个 dataframe ,其中每一行都移动了一个 position (使第一行消失,最后一行用NaN填充)。
To get (A1+A2)*(A2), you'll need to point at every cell below being A1 the actual cell df["A"] and A2 the cell below (df["A"].shift(-1))要获得 (A1+A2)*(A2),您需要将每个单元格指向 A1 下方的实际单元格df["A"]和 A2 下方的单元格(df["A"].shift(-1 ))
You can do this:你可以这样做:
For为了
a
0 1.0
1 3.0
2 5.0
3 2.0
then然后
df['d'] =(df['a']+df['a'].shift(-1))*df['a'].shift(-1)
gives给
a d
0 1.0 12.0
1 3.0 40.0
2 5.0 14.0
3 2.0 NaN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.