我想在索引1处选择一列,然后在索引2和5之间选择一个随机列。此代码适用于选择随机列:
train_cols = train.columns[[random.sample(range(2, 5), 1)]]
但是当我尝试在索引1处添加“常量”列时,它不起作用
train_cols = train.columns[1,[random.sample(range(2, 5), 1)]]
任何帮助都会很棒!谢谢
答案 0 :(得分:1)
让a
成为:
a = random.sample(range(2, 5), 1)
由于a
是一个列表,我只是这样做才能使它工作:
train_cols = train.columns[[1,a[0]]]
答案 1 :(得分:1)
值body
基本上是一维的numpy数组,所以你应该看一下http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html。
我们以此数组为例:
train.columns
(1)使用整数进行索引将返回该位置的元素:
In [2]: x = np.array(['a', 'b', 'c', 'd', 'e', 'f'])
(2)使用列表进行索引将返回给定位置的值数组:
In [3]: x[3]
Out[3]: 'd'
(3)在列表中使用多个值 not 的索引用于多维数组,因此在我们的情况下不起作用:
In [4]: x[[3, 5]]
Out[4]:
array(['d', 'f'],
dtype='|S1')
现在,In [5]: x[3, 5]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-8-37ec23c8a033> in <module>()
----> 1 x[3, 5]
IndexError: too many indices for array
返回一个列表,所以上面的第一个命令是这样的:
random.sample
但是你的第二个命令会执行类似In [6]: x[[[2]]]
Out[6]:
array(['c'],
dtype='|S1')
的操作,但由于同样的原因,上面的#3无法正常工作。
你想要的是x[1, [[2]]]
,最好的方法就是:
x[[1, 2]]
这将起作用,因为In[7]: x[[1, random.randint(2, 4)]]
返回一个整数而不是列表。