简体   繁体   English

选择熊猫列“ a”,“ b”和“ e”至“ g”

[英]Selecting pandas columns 'a', 'b' and 'e' through 'g'

Let's say I have a pandas dataframe with columns 'a', 'b', 'c', 'd', 'e', 'f', 'g'. 假设我有一个熊猫数据框,其中包含列“ a”,“ b”,“ c”,“ d”,“ e”,“ f”,“ g”。 I want to select columns 'a', 'b' and 'e' through 'g'. 我想通过“ g”选择列“ a”,“ b”和“ e”。 I don't want to explicitly specify the column names 'e' though 'g' as 'e', 'f', 'g' rather use something like 'e':'g'. 我不想通过“ g”将列名“ e”显式指定为“ e”,“ f”,“ g”,而是使用类似“ e”:“ g”的名称。 Is there any way possible to combine these 'a', 'b' and 'e':'g' in one? 有没有可能将这些“ a”,“ b”和“ e”:“ g”组合在一起?

What I have for now is this using pd.concat() 我现在拥有的是使用pd.concat()

pd.concat([df[:, 'a', 'b']), df[:, ['e': 'g']]], axis = 1)

使用RegEx:

df.loc[:,df.columns.str.match('[ab]|[e-g]')]

Use DataFrame.filter : 使用DataFrame.filter

df = pd.DataFrame({'a':list('abcdef'),
                   'b':[4,5,4,5,5,4],
                   'c':[7,8,9,4,2,3],
                   'd':[1,3,5,7,1,0],
                   'e':[5,3,6,9,2,4],
                   'f':list('aaabbb'),
                   'g':[0,3,5,7,1,0],
                   'h':[2,30,50,7,1,0],})

df = df.filter(regex='[ab]|[e-g]')
print (df)

   a  b  e  f  g
0  a  4  5  a  0
1  b  5  3  a  3
2  c  4  6  a  5
3  d  5  9  b  7
4  e  5  2  b  1
5  f  4  4  b  0

Another solution: 另一个解决方案:

rng = df.loc[:, 'e': 'g'].columns.tolist()
#alternative
#rng = df.columns[df.columns.get_loc('e'): df.columns.get_loc('g') + 1].tolist()

cols = ['a','b'] + rng
df = df[cols]
print (df)

   a  b  e  f  g
0  a  4  5  a  0
1  b  5  3  a  3
2  c  4  6  a  5
3  d  5  9  b  7
4  e  5  2  b  1
5  f  4  4  b  0

Based on the official pandas documentation you should be able to do just that! 根据熊猫的官方文档,您应该可以做到这一点! Select df['e':'g'] . 选择df['e':'g']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM