【问题标题】:'TypeError: only integer scalar arrays can be converted to a scalar index' when extracting elements from array'TypeError:从数组中提取元素时,只能将整数标量数组转换为标量索引'
【发布时间】:2020-09-19 21:39:32
【问题描述】:

我正在尝试通过调用一维数组中的索引来从数据帧的数组列中提取某些索引。

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

我用这种方法提取元素-

df['arr1']=df['arr'].apply(lambda x:itemgetter(*range1)(x))
df['arr2']=df['arr'].apply(lambda x:itemgetter(*range2)(x))

但得到了错误-

TypeError: only integer scalar arrays can be converted to a scalar index

我尝试使用-将范围转换为整数类型-

df['arr1'] = np.array(df['arr'])[range1.astype(int)]

但得到了错误-

AttributeError: 'tuple' object has no attribute 'astype'

然后我尝试了-

df['arr1'] = np.array(df['arr'])[int(range1)]

但得到了错误-

TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'

不知道如何继续。

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

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

    range1 = i[np.where((i>=0) & (i<=2))]
    range2 = i[np.where((i>=3) & (i<=4))]
    

    即创建一个包含 where 指示的 i 元素的数组, 所以结果也是 ndarray 具有分别过滤的内容。

    注意np.where((i&gt;=0) &amp; (i&lt;=2)) 单独产生一个生成器 理解包含(array([0, 1, 2], dtype=int64),),即:

    • 由单个元素组成的元组
    • 此元素是一个 ndarray,其中包含 [0, 1, 2]

    所以这样的元组不能作为itemgetter的参数,而是在 建议更改您的代码每个 range 包含一个 Numpy 数组, 你可以在那里使用。

    另外 2 个可能更自然的解决方案:将两个范围都定义为普通的 pythonic 列表:

    range1 = [0, 1, 2]
    range2 = [3, 4]
    

    Numpy数组:

    range1 = np.arange(3)
    range2 = np.arange(3, 5)
    

    【讨论】:

    • 感谢您的解释,但在我的情况下,我是一个 2000 元素的一维数组,我希望从该数组中提取指定范围内的索引位置,以便我可以从我的数据框数组中提取项目那些非常索引的列。因此,我不希望 i 的元素由 where 指示,因为范围 1 和 2 的顺序不明确为 0、1、2、3...我想要索引本身。
    • 例如,我试图从 i 中提取索引,其中值范围从 100 到 200,并且相应的索引出现为 [306, 307, 308, 309, 310, 311, 312 , 313, 314, 315, 316, 317, 318],然后我想从我的数据框的数组列中提取这些索引处的值。
    • 要从给定的索引中提取 Series(比如 s)的元素,请使用 s.loc[indices]
    猜你喜欢
    • 2020-04-30
    • 2020-07-23
    • 2019-03-15
    • 2020-04-20
    • 2021-01-17
    • 2020-03-12
    • 2021-02-09
    • 1970-01-01
    • 2019-01-09
    相关资源
    最近更新 更多