Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

python - How to perform complex arithmetic operations on dataframe/series/list?

I have a pandas dataframe on which I want to perform iterations on rows and perform the complex arithmetic operation. Given below is my dataframe:.

print(df1)

        A
     0  1
     1  2
     2  3
     3  4
     4  5
     6  7
     7  8

I want to get summation of first two rows and divide it by the value of the third row. This will be one iteration. During the iteration, if the values of x and y(in complex_operation function) reaches second-last and last rows respectively then, the value of z automatically becomes 1 to avoid Zero-Division error.

I have tried the following:.

Approach #1:

def complex_operation(x, y, z):
    return (x + y) / z

print(df1.apply(complex_operation, df1['A']))

Approach #1 results in

TypeError: 'Series' objects are mutable, thus they cannot be hashed

Approach #2:

print(df1['A'].apply(lambda x, y, z: (x + y) / z))

Approach #2 results in

TypeError: () missing 2 required positional arguments: 'y' and 'z'

I appreciate your time and efforts in helping me with this problem.

Expected Output:

        A
     0  1
     1  1.25
     2  1.4
     3  1.28
     4  1.5
     6  15

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

See the example below, if you had three columns : A,B,C:

df1['result'] = df1.apply(lambda x: complex_operation(x['A'], x['B'], x['C']), axis=1)

or if you want to print:

print(df1.apply(lambda x: complex_operation(x['A'], x['B'], x['C']), axis=1))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...