Home > OS >  AssertionError: <class 'method'> when trying to add two pandas df columns
AssertionError: <class 'method'> when trying to add two pandas df columns

Time:05-10

I did the following to add to the existing df

df['std'] = df[df['growth'].notnull()].groupby('id')['growth'].transform('std').astype(float)

my df is

id  growth   std
A    0.2    0.124
A    0.3    0.124
A    0.5    0.124
B     1     0.216
B    0.5    0.216
B    0.6    0.216
C
...

then i did the following

df['ratio'] = df.growth / df.std

which should be a simple task but i get the following error msg. I am so confused as to why?

Here is the full traceback.

TypeError                                 Traceback (most recent call last)
/usr/lib/python3/dist-packages/pandas/core/ops/__init__.py in na_op(x, y)
    967         try:
--> 968             result = expressions.evaluate(op, str_rep, x, y, **eval_kwargs)
    969         except TypeError:

/usr/lib/python3/dist-packages/pandas/core/computation/expressions.py in evaluate(op, op_str, a, b, use_numexpr, **eval_kwargs)
    220     if use_numexpr:
--> 221         return _evaluate(op, op_str, a, b, **eval_kwargs)
    222     return _evaluate_standard(op, op_str, a, b)

/usr/lib/python3/dist-packages/pandas/core/computation/expressions.py in _evaluate_standard(op, op_str, a, b, **eval_kwargs)
     69     with np.errstate(all="ignore"):
---> 70         return op(a, b)
     71 

TypeError: unsupported operand type(s) for  : 'float' and 'method'

During handling of the above exception, another exception occurred:
: <class 'method'>

I checked dtype and std, growth are both float???

CodePudding user response:

pandas.DataFrame.std is built-in method, use [] for indexing columns in this case

df['ratio'] = df['growth'] / df['std']
  • Related