简体   繁体   English

如何计算 pandas dataframe 中的列?

[英]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.

相关问题 如何使用公式计算每7个列的平均值? - How to calculate the average for every 7 colums with a formula? 如何对 Pandas 数据框 Excel 导入进行排序? - How do I sort a Pandas dataframe Excel import? 如何查找在不同列中出现一次或多次的名称 - How do I find names that appear once or more times in different colums 我如何将 plot 列为一个包含 57 行和 2820 列数据的图表? - How do i line plot a chart, with 57 rows, and 2820 colums of data? 如果使用熊猫在另一个数据帧中不存在列值,如何将它们从一个数据帧合并到另一个数据帧 - How do I merge column values from one dataframe to another if they are not present in another using pandas 如何从Excel获取行,然后将其作为列放入Pandas数据框中? - How do I get row from Excel and then put it into a Pandas dataframe as a column? 如何在熊猫的数据框中绘制箭头? - How can I draw an arrow in a dataframe in pandas? 如何制作从大型 xlsx 文件加载 pandas DataFrame 的进度条? - How do I make a progress bar for loading pandas DataFrame from a large xlsx file? 我该如何计算时间? 整个午夜 - How do I calculate this time? Across midnight 如何将应用过滤器应用于工作表的3个不同Colums - How can I apply apply filter to 3 different Colums of a worksheet
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM