【发布时间】: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'
不知道如何继续。
【问题讨论】: