Zegary
Zegary

Reputation: 3

Changing the order in a list by comparing it to another list

I am having trouble manipulating the element's place in my list. I have the following code:

name= ['a', 'b', 'c','d','e']
year= [10,20,30,40,50]
ID= ['a', 'c', 'd']
df = pd.DataFrame({'Name' : name, 'age' : year})
x= list(set(name).intersection(ID))
print (x)
y=df[df['Name'].isin(x)]['age']
print(y)

The output I get is:

['c', 'a', 'd']
0    10
2    30
3    40

This is where I am confused. List name and year are supposed to be related, so a and 10, b and 20.... But when I print x and y, I get c and 10, a and 30, b and 40. I think python automatically sorts y from ascending to descending. How do I fix y to get 30, 10, 40 instead of 10, 30, 40.

Upvotes: 0

Views: 101

Answers (2)

CumminUp07
CumminUp07

Reputation: 1978

To get what you are looking for you can just use the same subset from the df, like this

name= ['a', 'b', 'c','d','e']
year= [10,20,30,40,50]
ID= ['a', 'c', 'd']
df = pd.DataFrame({'Name' : name, 'age' : year})
x= list(set(name).intersection(set(ID)))
print (x)
y=df[df['Name'].isin(x)].age.to_list()
y1= df[df['Name'].isin(x)].Name.to_list()
print(y)
print(y1)

result

[10, 30, 40]
['a', 'c', 'd']

y and y1 will print out how you are expecting, where they are matched

Upvotes: 1

user8060120
user8060120

Reputation:

You confused because after convert list to set you break the order of the original list, so to fix it:

instead

x= list(set(name).intersection(ID))

you should filter your original list, for example by list comprehension:

x= [i for i in name if i in ID]

Upvotes: 2

Related Questions