How to do a subtraction operation between two columns of a dataframe and then add the result with another column?

Asked

Viewed 440 times

3

I have this code:

dados_train = pd.read_csv('arquivo.csv', delimiter=",")
y = ((dados_train.pop('col_name1') - dados_train.pop('col_name2')) + (dados_train.pop('col_name2')

When I try to run just like this:

y = (dados_train.pop('col_name1') - dados_train.pop('col_name2')

Works!

But when I try:

y = ((dados_train.pop('col_name1') - dados_train.pop('col_name2')) + (dados_train.pop('col_name2')

Makes a mistake!

Why does this happen? Someone would know a solution?

2 answers

1

When you use the pop it deletes the value of the variable, then the second time you actually use it there is no value in it

you can do so

y = (dados_train['col_name1'] - dados_train['col_name2']) + dados_train['col_name2']

if you use it in dictionary, you have the option of get, I don’t know if the dados_train is receiving a dictionary, but if I was can use it like this

y = (dados_train.get('col_name1') - dados_train.get('col_name2')) + dados_train.get('col_name2')

1


the method list pop.() remove an object from the last position of the list and return it to the user. As presented, I believe the list has only two elements.

try to access using brackets:

y = (dados_train['col_name1'] - dados_train['col_name2'] + dados_train['col_name2'])

Addendum: you forgot to close one of the pairs of parentheses. I closed it in the example, but this may be the problem in your application.

  • 1

    Thank you Arthur! Well that’s right! Now it worked!

  • If the answer below solved your problem and there was no doubt left, mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved. If you still have any questions or would like further clarification, feel free to comment.

  • You can only mark an answer as accepted, but, if you wish, you can vote for all who you think have solved the problem. Feel free

Browser other questions tagged

You are not signed in. Login or sign up in order to post.