简体   繁体   中英

Python - Applying function to 2D array

I have a 2D array converted from a CSV spreadsheet with data using pandas. I would like to apply a function on the data that also includes elements of the array.

My function:

def calc_pol(a, b, R = 0.08314462618, T = 298.15):
           return a * b * R * T

I can call it on the data array in the following manner, where a and b are determined from the data array:

calc_pol(
        a = data[0,0], b=data[0,1]
        )

Which will return the value I'm looking for. Now, the organization of the spreadsheet was in columns so the way the data is incorporated is that if I:

print(data[0])

I get the following (arbitrary) values:

20 40 60 80 100 120

I want to feed my function 20*40 (data[0,0]| * data[0,1]) --> save value in new array. 60 * 80 (data[0,2]| * data[0,3]) --> save value in new array and do the same for 80 * 100.

Each "column" has 80 values, so I would like to iterate over i in range 0: 80, by employing a for loop or some other function but I am unsure on how to proceed, my index keeps "getting out of range. I appreciate any insights you can offer!

What you are describing sounds like a simple column operation in pandas, there is no need to use indexing by number or for loop if you have column names:

import pandas as pd

df = pd.DataFrame({'c'+str(i):[i]*4 for i in range(6)})

def calc_pol(df, col1, col2, R = 0.08314462618, T = 298.15):
    return df[col1] * df[col2] * R * T

df['c6'] = calc_pol(df, 'c1', 'c2', R = 0.08314462618, T = 298.15)
df['c7'] = calc_pol(df, 'c3', 'c4', R = 0.08314462618, T = 298.15)
    c0  c1  c2  c3  c4  c5  c6          c7
0   0   1   2   3   4   5   49.579141   297.474844
1   0   1   2   3   4   5   49.579141   297.474844
2   0   1   2   3   4   5   49.579141   297.474844
3   0   1   2   3   4   5   49.579141   297.474844

You can use a list comprehension and store all the results in the res list:

number_of_rows = 80
res = [calc_pol(a = data[0,i], b=data[0,i+1]) for i in range(number_of_rows - 1)]

at this point res[0] contains 20*40 , res[1] contains 60 * 80 and so on...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM