0

I am trying to add a column of a dataframe to itself by calling the column using the . method. However Python gives me an error which I don't understand. This is the code:

In [29]:
gdp_pop.head()
Out[29]:

        date    country         gdp  series_code_x       pop series_code_y
0 1990-01-01  Australia  158051.132  NYGDPMKTPSAKD  17065100   SP.POP.TOTL
1 1990-04-01  Australia  158263.582  NYGDPMKTPSAKD  17065100   SP.POP.TOTL
2 1990-07-01  Australia  157329.279  NYGDPMKTPSAKD  17065100   SP.POP.TOTL
3 1990-09-01  Australia  158240.678  NYGDPMKTPSAKD  17065100   SP.POP.TOTL
4 1991-01-01  Australia  156195.954  NYGDPMKTPSAKD  17284000   SP.POP.TOTL

In [30]:
gdp_pop.dtypes['pop']
Out[30]:
dtype('int64')

In [31]:
gdp_pop.pop + gdp_pop.pop
Traceback (most recent call last):
  File "<stdin>", line 72, in exceptionCatcher
    raise exception
  File "<stdin>", line 3361, in run_ast_nodes
    if (await self.run_code(code, result,  async_=asy)):
  File "<stdin>", line 3458, in run_code
    self.showtraceback(running_compiled_code=True)
  File "<stdin>", line 2066, in showtraceback
    self._showtraceback(etype, value, stb)
  File "<stdin>", line 72, in exceptionCatcher
    raise exception
  File "<stdin>", line 3441, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<stdin>", line 1, in <module>
    gdp_pop.pop + gdp_pop.pop
TypeError: unsupported operand type(s) for +: 'method' and 'method'

Does anyone know what's going wrong here?

Amin Shn
  • 532
  • 2
  • 11
  • 1
    Does this answer your question? [What is the difference between using squared brackets or dot to access a column?](https://stackoverflow.com/questions/41130255/what-is-the-difference-between-using-squared-brackets-or-dot-to-access-a-column) – fsimonjetz Feb 27 '22 at 12:08
  • @fsimonjetz no it doesn't, my problem is not just creating a new variable. df.x1 / df.x2 doesn't work in my case, but in the link you shared it says df.a + df.b works. – Amin Shn Feb 27 '22 at 12:25
  • Can you post a minimal reproducible example? What do you mean by "it doesn't work"? Do you get any error? – fsimonjetz Feb 27 '22 at 12:30
  • I can't post a reproducible example because when I try it using simulated data I don't get the error. it just happens when I use the above specific data. – Amin Shn Feb 27 '22 at 12:49
  • 3
    The one thing is you cant do operations by access the variable in a dataframe in the form dataframe.column_name when the column name is equal to one of the methods we use in python. Here the column name pop refers to method pop we use for lists to remove and print one of the value from list. Hence you are getting that error – Yagami_Light Feb 27 '22 at 12:54
  • @Yagami_Light I see! thanks yes thats the problem. I didn't know there exist a pop method – Amin Shn Feb 27 '22 at 13:00

0 Answers0