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

How to get the columns names orderly acorrding to the list in python using for loop

I have a problem. I have a list which contains data frame column names it should match with the data frame if the name is matched it should get appended in a new list. I wrote code which does that but the names are getting appended according to the sequence of data frame but not according to list. How do I do that?

Input: 
col_lst = ['hj','pl','fgc','bc','drt']
df=
   abc bc  fgc drt  
0  0   q   d  3  
1  0   g   t  1  
2  0   a   g  4 
3  0   d   c  5  
4  0   h   b  6

My code:

lst=[]
for i in df:
       for j in col_lst:
              if i in j:
                  lst.append(j)

I get the Ouput like this lst =['bc','fgc','drt']

what I want is lst = ['fgc ','bc','drt']

question from:https://stackoverflow.com/questions/65948829/how-to-get-the-columns-names-orderly-acorrding-to-the-list-in-python-using-for-l

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

1 Reply

0 votes
by (71.8m points)

If you can do like this give the name as listwise see following stuff

col_lst = ['hj','pl','fgc','bc','drt']
lst=[]
for j in col_lst: 
   if j in df.columns: 
       lst.append(j) 
print(lst)

output will be

['fgc ','bc','drt']

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

...