pandas 熊猫将一行除以另一行并输出到同一数据帧中的另一行

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

Pandas divide one row by another and output to another row in the same dataframe

pythonpandas

提问by dvanic

For a Dataframe such as:

对于数据框,例如:

      dt
                COL000  COL001
      STK_ID                
      Rowname1  2  2
      Rowname2  1  4
      Rowname3  1  1

What's the easiest way to append to the same data frame the result of dividing Row1 by Row2? i.e. the desired outcome is:

将 Row1 除以 Row2 的结果附加到同一数据帧的最简单方法是什么?即期望的结果是:

                COL000  COL001
      STK_ID                
      Rowname1  2  2
      Rowname2  1  4
      Rowname3  1  1
      Newrow    2  0.5

Sorry if this is a simple question, I'm slowly getting to grips with pandas from an R background.

对不起,如果这是一个简单的问题,我正在慢慢掌握 R 背景下的Pandas。

Thanks in advance!!!

提前致谢!!!

采纳答案by Ffisegydd

The code below will create a new rowwith index dwhich is formed from dividing rows aand b.

下面的代码将创建一个带有索引的新行,该索引d由分隔行ab.

import pandas as pd

df = pd.DataFrame(data={'x':[1,2,3], 'x':[4,5,6]}, index=['a', 'b', 'c'])

df.loc['d'] = df.loc['a'] / df.loc['b']

print(df)
#      x    y
# a  1.0  4.0
# b  2.0  5.0
# c  3.0  6.0
# d  0.5  0.8

回答by acushner

in order to access the first two rows without caring about the index, you can use:

为了在不关心索引的情况下访问前两行,您可以使用:

df.loc['newrow'] = df.iloc[0] / df.iloc[1]

then just follow @Ffisegydd's solution...

然后只需按照@Ffisegydd 的解决方案...

in addition, if you want to append multiple rows, use the pd.DataFrame.appendfunction.

此外,如果要追加多行,请使用该pd.DataFrame.append函数。

回答by Victor

pandas does all the work row by row. By including another element it also interprets you want a new column:

Pandas逐行完成所有工作。通过包含另一个元素,它还解释了您想要一个新列:

data['new_row_with_division'] = data['row_name1_values'] / data['row_name2_values']