pandas 将索引号转换为 int (Python)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48528348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert index number to int (Python)
提问by Renan Andrade
EDIT:The .mean() function works just right:
编辑:.mean() 函数工作得恰到好处:
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
我有一个 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)
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''
回答by Scott Boston
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)
回答by ltd9938
Cast last_id as an int.
将 last_id 转换为 int。
print(t_age/int(last_id))
print(t_age/int(last_id))
回答by user15051990
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()
回答by juanpa.arrivillaga
Your fundamental probelm is that iloc
is suppose to be used with __getitem__
not with __call__
, in other words:
您的基本问题是iloc
假设与__getitem__
not with 一起使用__call__
,换句话说:
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.
前者创建了一个索引器对象,这不是你想要的。你想索引.
回答by Renan Andrade
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()