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
95 views
in Technique[技术] by (71.8m points)

python - Is there a case sensitive method to filter columns in a dataframe by header?


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

1 Reply

0 votes
by (71.8m points)

You can use df.filter with the regex parameter:

df.filter(regex=r'(?i)^i')

this will return columns starting with I ignoring the case. Regex Demo

Example below:

Lets consider the input dataframe:

df = pd.DataFrame(np.random.randint(0,20,(5,4)),
      columns=['itest','Itest','another','anothericol'])

print(df)

   itest  Itest  another  anothericol
0      1      4       14           17
1     17     10       14            1
2     16     18       10            7
3     10     12       17           14
4      6     15       17           19 

With df.filter

print(df.filter(regex=r'(?i)^i'))

   itest  Itest
0      1      4
1     17     10
2     16     18
3     10     12
4      6     15

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

...