如何选择结合了列表和范围的数据框列 [英] How to select dataframe columns with lists and ranges combined

查看:59
本文介绍了如何选择结合了列表和范围的数据框列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑此df:

df = pd.DataFrame({'a':[1,2], 'b':[1,2], 'c':[1,2], 'd':[1,2], 'e':[1,2], 'f':[1,2], 'g':[1,2], 'h':[1,2]})

   a  b  c  d  e  f  g  h
0  1  1  1  1  1  1  1  1
1  2  2  2  2  2  2  2  2

如何选择第一,第四和第五至第七列? 我尝试过的:

How can I select the 1st, 4th, and 5th-7th columns? What I tried:

df.iloc[:, [0, 3, np.arange(5,8)]]

ValueError: setting an array element with a sequence.

推荐答案

您可以执行以下操作:

df.iloc[:, [0, 3] + list(range(5,8))]

[0, 3] + list(range(5,8))连接两个列表,将您的显式列表与从所需范围派生的列表组合在一起.

[0, 3] + list(range(5,8)) concatenates 2 lists, combining your explicit list with a list derived from your desired range.

或者,您可以使用 为您建立索引数组:

Alternatively, you can use numpy.r to build an indexing array for you:

import numpy as np

df.iloc[:, np.r_[0,3,5:8]]

np.r_[0,3,5:8]  # array([0, 3, 5, 6, 7])

例如,如果您有多个范围,这将很有用.

This would be useful, for example, if you have multiple ranges.

这篇关于如何选择结合了列表和范围的数据框列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆