如何使用两行值在Pandas中的行之间应用用户定义的函数?

jm81lzqq  于 2022-12-02  发布在  其他
关注(0)|答案(1)|浏览(114)

I have two rows of data in a Pandas data frame and want to operate each column separately with a function that includes both values e.g.

import pandas as pd    
df = pd.DataFrame({"x": [1, 2], "z": [2, 6], "i": [3, 12], "j": [4, 20], "y": [5, 30]})
    x   z   i   j   y
0   1   2   3   4   5
1   2   6   12  20  30

The function is something like the row 2 val minus row 1 val, divided by the latter - for each column separately e.g.
(row2-row1)/row2
so I can get the following

0.5  0.667   0.75   0.8   0.833

Based on the following links
how to apply a user defined function column wise on grouped data in pandas
https://www.geeksforgeeks.org/apply-a-function-to-each-row-or-column-in-dataframe-using-pandas-apply/
https://pythoninoffice.com/pandas-how-to-calculate-difference-between-rows
Groupby and apply a defined function - Pandas
I tried the following

df.apply(lambda x,y: (x + y)/y, axis=0)

This does not work as it expects y as an argument

df.diff()

This works but then it is not exactly the function I want.
Does anyone know how to achieve the result I expect?

bmp9r5qi

bmp9r5qi1#

df.diff(1).div(df)

输出功率

x   z    i    j   y
0   NaN NaN  NaN  NaN NaN
1   0.5 0.67 0.75 0.8 0.83

我用了一个简短的例子来回答。如果我误解了什么,把你的例子编辑得更长一些。我会再回答一次。

相关问题