Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

python - How to select dataframe columns with lists and ranges combined

Please consider this 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.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this:

df.iloc[:, [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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...