Joonatan
Joonatan

Reputation: 59

Python loop multiple positional arguments to function from dataframe or array

I have .csv file with colums A and B, and rows with values.

A, B
232.65, -57.48
22.69, -5.46
23.67, -7.71

I want to loop these values with function.

So lets create simple function with 2 positional parameters:

def add_numbers(n1, n2):
    answer = n1+n2
    print(answer)
#lets read the file:
import pandas as pd
df= pd.read_csv(r'myfile.csv')

print(df[A]) #just checking the column A for this example, but column B is also required for n2.
0   232.65
1   22.69
3   23.67


  1. I could also transfer those colums to array but I still could not loop it. How would I loop these with the function that requires two arguments?

arr = np.loadtxt(r'myfile.csv', delimiter=',')
arr

array([[232.65, -57.48],
       [22.69, -5.46],
       [23.67, -7.71],

I have been trying to loop with various ways and iter and enumerate and apply, but I keep doing something slightly wrong.

Cheer, Joonatan

Upvotes: 0

Views: 227

Answers (3)

Shivai chaudhari
Shivai chaudhari

Reputation: 21

try:

import pandas as pd

df = pd.DataFrame({
    'A': [232.65,22.69,23.67],
    'B':[-57.48,-5.46,-7.71]
})


def add_numbers(n1, n2):
    answer = n1+n2
    print(answer)

for i in range(len(df)):
    n1 = df.loc[i,'A']
    n2 = df.loc[i,'B']
    add_numbers(n1,n2)

output:

175.17000000000002
17.23
15.96

Upvotes: 1

Muhammad Ali
Muhammad Ali

Reputation: 489

I hope, it works for your solution. Whenever you have to apply a custom function and want to loop through values to perform an operation use apply function.

Code:

import pandas as pd
df = pd.read_csv('./loop_through_2_columns.csv')
def add_numbers(n1, n2):
    answer = n1+n2
    return answer
df['result'] = df.apply(lambda x: add_numbers(x.A, x.B), axis=1) 
df.head()

Output:

      A       B     result
0   232.65  -57.48  175.17
1   22.69   -5.46   17.23
2   23.67   -7.71   15.96

Upvotes: 1

Megatom
Megatom

Reputation: 71

You can loop and pass the values in each row to add_numbers. Then use iterrows to get the index and row values.

def add_numbers(n1, n2):
answer = n1 + n2
print(answer)
    
import pandas as pd
df = pd.read_csv(r'myfile.csv')
    
for index, row in df.iterrows():
    add_numbers(row['A'], row['B'])

Upvotes: 1

Related Questions