11

EDIT: The .mean() function works just right:

renda['age'].mean()

I'm still not sure why the errors mentioned below and in the answers happened, but this helps as a shortcut.


I got a DataFrame renda in which there's a column age and I need to get the mean of the ages. I wrote

t_age = renda['age'].sum()
renda.index = renda.index.map(int) #intended solution
last_id = renda.iloc(-1)
print(t_age/last_id)

Trying to adapt the answers from here. It still doesn't work though and this error is raised:

TypeError: unsupported operand type(s) for /: 'int' and '_iLocIndexer'

What can I do to solve this? Thank you!


@ScottBoston:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/opt/conda/lib/python3.6/site-packages/pandas/core/ops.py in na_op(x, y)
    657             result = expressions.evaluate(op, str_rep, x, y,
--> 658                                           raise_on_error=True, **eval_kwargs)
    659         except TypeError:

/opt/conda/lib/python3.6/site-packages/pandas/core/computation/expressions.py in evaluate(op, op_str, a, b, raise_on_error, use_numexpr, **eval_kwargs)
    210         return _evaluate(op, op_str, a, b, raise_on_error=raise_on_error,
--> 211                          **eval_kwargs)
    212     return _evaluate_standard(op, op_str, a, b, raise_on_error=raise_on_error)

/opt/conda/lib/python3.6/site-packages/pandas/core/computation/expressions.py in _evaluate_numexpr(op, op_str, a, b, raise_on_error, truediv, reversed, **eval_kwargs)
    121     if result is None:
--> 122         result = _evaluate_standard(op, op_str, a, b, raise_on_error)
    123 

/opt/conda/lib/python3.6/site-packages/pandas/core/computation/expressions.py in _evaluate_standard(op, op_str, a, b, raise_on_error, **eval_kwargs)
     63     with np.errstate(all='ignore'):
---> 64         return op(a, b)
     65 

/opt/conda/lib/python3.6/site-packages/pandas/core/ops.py in <lambda>(x, y)
     96                           default_axis=default_axis, reversed=True),
---> 97         rtruediv=arith_method(lambda x, y: operator.truediv(y, x),
     98                               names('rtruediv'), op('/'), truediv=True,

TypeError: unsupported operand type(s) for /: 'int' and 'str'

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
/opt/conda/lib/python3.6/site-packages/pandas/core/ops.py in safe_na_op(lvalues, rvalues)
    681             with np.errstate(all='ignore'):
--> 682                 return na_op(lvalues, rvalues)
    683         except Exception:

/opt/conda/lib/python3.6/site-packages/pandas/core/ops.py in na_op(x, y)
    667                 mask = notnull(x)
--> 668                 result[mask] = op(x[mask], y)
    669             else:

/opt/conda/lib/python3.6/site-packages/pandas/core/ops.py in <lambda>(x, y)
     96                           default_axis=default_axis, reversed=True),
---> 97         rtruediv=arith_method(lambda x, y: operator.truediv(y, x),
     98                               names('rtruediv'), op('/'), truediv=True,

TypeError: unsupported operand type(s) for /: 'int' and 'str'

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-71-d5969a714aff> in <module>()
      3 renda.index = renda.index.astype(int) #use astype to convert to int
      4 last_id = renda.iloc[-1] #Square brackets
----> 5 print(t_age/last_id)

/opt/conda/lib/python3.6/site-packages/pandas/core/ops.py in wrapper(left, right, name, na_op)
    719                 lvalues = lvalues.values
    720 
--> 721         result = wrap_results(safe_na_op(lvalues, rvalues))
    722         return construct_result(
    723             left,

/opt/conda/lib/python3.6/site-packages/pandas/core/ops.py in safe_na_op(lvalues, rvalues)
    690                 if is_object_dtype(lvalues):
    691                     return libalgos.arrmap_object(lvalues,
--> 692                                                   lambda x: op(x, rvalues))
    693             raise
    694 

pandas/_libs/algos_common_helper.pxi in pandas._libs.algos.arrmap_object (pandas/_libs/algos.c:31954)()

/opt/conda/lib/python3.6/site-packages/pandas/core/ops.py in <lambda>(x)
    690                 if is_object_dtype(lvalues):
    691                     return libalgos.arrmap_object(lvalues,
--> 692                                                   lambda x: op(x, rvalues))
    693             raise
    694 

/opt/conda/lib/python3.6/site-packages/pandas/core/ops.py in <lambda>(x, y)
     95         rsub=arith_method(lambda x, y: y - x, names('rsub'), op('-'),
     96                           default_axis=default_axis, reversed=True),
---> 97         rtruediv=arith_method(lambda x, y: operator.truediv(y, x),
     98                               names('rtruediv'), op('/'), truediv=True,
     99                               fill_zeros=np.inf, default_axis=default_axis,

TypeError: ufunc 'true_divide' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

@juanpa.arrivillaga: enter image description here

Renan Andrade
  • 169
  • 1
  • 2
  • 11

5 Answers5

8

I think you need this:

t_age = renda['age'].astype(int).sum()
renda.index = renda.index.astype(int) #use astype to convert to int
last_id = renda.iloc[-1] #Square brackets
print(t_age/last_id)
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
  • @RenanAndrade I don't see any syntax errors in your image. – Scott Boston Jan 30 '18 at 18:55
  • 1
    @RenanAndrade what errors? Please provide full error messages as *formatted text* in the question itself. – juanpa.arrivillaga Jan 30 '18 at 19:01
  • Sorry, I didn't know which errors were relevant, so I thought creating that file would be better. I didn't type it here because it exceeded the max of characteres (and not in the question because the errors I referenced just above were about this answer). – Renan Andrade Jan 31 '18 at 18:13
  • @RenanAndrade your link above just has this in it: `{"success":false,"error":404,"message":"Not Found"}` – Scott Boston Jan 31 '18 at 18:15
  • I'll try pasting it in the question, then. I also found out about the mean() function and I believe it might work. – Renan Andrade Jan 31 '18 at 18:19
  • You still have some dtype issues. What does type(t_age) return and what does type(last_id) return? – Scott Boston Jan 31 '18 at 18:26
  • `type(t_age)` returns `numpy.int64` and `type(last_id)` returns `pandas.core.series.Series`. I've tried pasting the new solution and it raises `TypeError: ufunc 'true_divide' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''`. – Renan Andrade Feb 01 '18 at 02:05
  • `type(t_age)` returns `numpy.int64` and `type(last_id)` returns `pandas.core.series.Series`. I've tried pasting the new solution and it raises `TypeError: ufunc 'true_divide' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''`. – Renan Andrade Feb 01 '18 at 02:05
3

Convert index to column and then, you will be able to take mean of column using the code below.

   render=render.reset_index(level=['age'])# Convert index to column
   render['age']=render.age.astype(str)
   age_mean=render['age'].mean()
Pang
  • 9,564
  • 146
  • 81
  • 122
user15051990
  • 1,835
  • 2
  • 28
  • 42
  • I tried reseting `renda` to `render` and I get `KeyError: 'Level age must be same as name (None)'`. If I keep `renda` it says `render` isn't defined. – Renan Andrade Feb 01 '18 at 01:58
2

Your fundamental probelm is that iloc is suppose to be used with __getitem__ not with __call__, in other words:

last_id = renda.iloc(-1)

Should be:

last_id = renda.iloc[-1]

The former creates an indexer object, which is not what you want. You want to index.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
1

Cast last_id as an int.

print(t_age/int(last_id))

ltd9938
  • 1,444
  • 1
  • 15
  • 29
  • With and without the intended solution, this error is now raised: `TypeError: int() argument must be a string, a bytes-like object or a number, not '_iLocIndexer'` – Renan Andrade Jan 30 '18 at 18:47
1

I finally got it. I put comments on the code below in case someone is having the same issue and also for possible future reference:

t_age = renda['age'].sum() #gives total age. count() seems to work too
t_age_num = pd.to_numeric(t_age) #assures t_age is numeric
last_id = renda.iloc[-1] #finds the last row 
last_id_num = last_id.name #stores the last row's name

print(t_age_num/last_id_num)

A nice shortcut is:

renda['age'].mean()
Renan Andrade
  • 169
  • 1
  • 2
  • 11