Daniel
Daniel

Reputation: 23

How do I assign a value to a specific row and column by name?

I tried to iterate through each row in a dataframe, and to do this - calculate_distance_from_SnS(row), then reassign the returned value (its a number). The result is that it doesn't save the value under the specific column, what am I missing?

for example:

DF example

A   B   C
1   10  0
2   12  0

and I want to do this function C=A+B for each row and get to this state:

A   B   C
1   10  11
2   12  14

I did this:


def calculate_distance_from_SnS(row):

using DF row and using 2 cols to calculate.



for i,row in customers.iterrows():
    row['dist_from_sns'] = calculate_distance_from_SnS(row)

Upvotes: 1

Views: 2394

Answers (1)

jezrael
jezrael

Reputation: 862691

Set values of original DataFrame, not by Series in loop:

for i,row in customers.iterrows():
    customers.loc[i, 'dist_from_sns'] = calculate_distance_from_SnS(row)

But if possible, better is use DataFrame.apply with axis=1 for processing per rows:

f = lambda x: calculate_distance_from_SnS(x['lat'], x['long'])
customers['dist_from_sns'] = customers.apply(f, axis=1)

Upvotes: 1

Related Questions