user12441225
user12441225

Reputation:

How to iterate through columns in a dataframe and update the values?

I have some data in an excel file (a snippet of it is shown in the figure below:

enter image description here

I would like to iterate through each of the columns and update their values. I have attempted the following...however it gives me an error which is unclear: "KeyError: 32.5". Any help to get around this would be much appreciated!

def iterate (data, cost_T, int_T, cost_F, int_F):
     for i, j in zip(data.iloc[:, 0], data.iloc[:, 1]):
         data[i] = (data[i]- cost_T)/int_T
         data[j] = (data[j]- cost_F)/int_F
iterate (df, 455, 31, 501, 42)

Upvotes: 1

Views: 80

Answers (2)

Nori
Nori

Reputation: 2962

You can use DataFrame.map(function)

df['TT_a'] = df['TT'].map(lambda x:(x - 455) / 31)
df['FT_a'] = df['FT'].map(lambda x:(x - 501) / 42)

Upvotes: 1

sukhbinder
sukhbinder

Reputation: 1111

You could simply do this with two lines of code without a loop

data["TT"] = (data["TT"]-cos_T)/ini_T
data["FT"] = (data["FT"]-cos_F)/ini_F

Upvotes: 0

Related Questions