将索引号转换为int(Python)

时间:2018-01-30 18:37:35

标签: python pandas indexing int

编辑: .mean()函数运行正常:

renda['age'].mean()

我仍然不确定为什么下面和答案中提到的错误发生了,但这有助于作为捷径。

我有一个DataFrame renda,其中有age列,我需要得到年龄的平均值。我写了

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

尝试调整here的答案。它仍然无法正常工作,并且会出现此错误:

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

我该怎么做才能解决这个问题?谢谢!

@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

5 个答案:

答案 0 :(得分:2)

我认为你需要这个:

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)

答案 1 :(得分:2)

将索引转换为列,然后,您可以使用下面的代码获取列的平均值。

   render=render.reset_index(level=['age'])# Convert index to column
   render['age']=render.age.astype(str)
   age_mean=render['age'].mean()

答案 2 :(得分:1)

将last_id转换为int。

def sql_soap(tablename, *, where):

答案 3 :(得分:1)

您的基本问题是,iloc假设与__getitem__一起使用,而不是与__call__一起使用,换句话说:

last_id = renda.iloc(-1)

应该是:

last_id = renda.iloc[-1]

前者创建了一个索引器对象,这不是你想要的。您想要索引

答案 4 :(得分:1)

我终于明白了。我对下面的代码进行了评论,以防有人遇到同样的问题,以及将来可能的参考:

register.txt

一个很好的捷径是:

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)