Python ';TypeError:只能将整数标量数组转换为标量索引';从数组中提取元素时

Python ';TypeError:只能将整数标量数组转换为标量索引';从数组中提取元素时,python,pandas,numpy,Python,Pandas,Numpy,我试图通过从1D数组调用索引,从数据帧的数组列中提取某些索引 import pandas as pd import numpy as np from operator import itemgetter i = np.arange(10) range1 = np.where((i>=0) & (i<=2)) range2 = np.where((i>=3) & (i<=4)) df = pd.DataFrame(np.random.randn(10, 5

我试图通过从1D数组调用索引,从数据帧的数组列中提取某些索引

import pandas as pd
import numpy as np
from operator import itemgetter

i = np.arange(10)
range1 = np.where((i>=0) & (i<=2))
range2 = np.where((i>=3) & (i<=4))
df = pd.DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])
df['arr'] = df[['a', 'b', 'c', 'd', 'e']].values.tolist()
df
但是我犯了错误-

TypeError: only integer scalar arrays can be converted to a scalar index
AttributeError: 'tuple' object has no attribute 'astype'
TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'
我尝试使用-

df['arr1'] = np.array(df['arr'])[range1.astype(int)]
但是我犯了错误-

TypeError: only integer scalar arrays can be converted to a scalar index
AttributeError: 'tuple' object has no attribute 'astype'
TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'
于是我试着-

df['arr1'] = np.array(df['arr'])[int(range1)]
但是我犯了错误-

TypeError: only integer scalar arrays can be converted to a scalar index
AttributeError: 'tuple' object has no attribute 'astype'
TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'

不确定如何继续。

定义两个范围时,请将代码更改为:

range1 = i[np.where((i>=0) & (i<=2))]
range2 = i[np.where((i>=3) & (i<=4))]
或Numpy阵列:


定义这两个范围时,请将代码更改为:

range1 = i[np.where((i>=0) & (i<=2))]
range2 = i[np.where((i>=3) & (i<=4))]
或Numpy阵列:


感谢您的解释,但在我的例子中,我是一个2000元素的1d数组,我希望从该数组中提取指定范围内的索引位置,以便我可以从数据帧的数组列中提取这些索引处的项。因此,我不希望I的元素由where表示,因为范围1和2的顺序不是0,1,2,3…我想要索引本身。例如,我试图从I中提取索引,其中值范围为100到200,相应的索引显示为[306、307、308、309、310、311、312、313、314、315、316、317、318],然后我想从这些索引处的数据帧数组列中提取值。要从给定索引中提取系列元素(比如s),请使用s.loc[index]。感谢您的解释,但在我的例子中,我是一个2000元素的1d数组,我希望从该数组中提取指定范围内的索引位置,以便我可以从数据帧的数组列中提取这些索引处的项。因此,我不希望我的元素由where指示,因为范围1和2不具体在e顺序0,1,2,3…我想要索引本身。例如,我试图从I中提取索引,其中值范围为100到200,相应的索引显示为[306,307,308,309,310,311,312,313,314,315,316,317,318],然后我想从这些索引处的数据帧数组列中提取值。