I have two different lists with almost the same values but with different index values. I have some values in list_1
and need to extract index of those values in list_2
. Then I want to combine list_1
as ['Number']
column and index outcome as ['Index']
column in a Dataframe.
list_1 = ['1','2','3','4','5','6','7','8','9','10']
list_2 = ['12','11','10','9','8','6','5','4','3','2','1']
data = {"Number":pd.Series(list_1)}
df = pd.Dataframe(data,columns=["Number"])
list_index=[]
for i in df["Number"]:
if i in list_2:
index= pd.Index(list_2)
m = index.get_loc(i)
list_index.append(m)
df['Index']=list_index
Error is that quantity of values in df["Number"]
and list_index
are different.
But when I'm trying to add list_1
and m to DataFrame, I can't assign all the dedicated indices to the numbers in list_1
.
First you find the indices of elements in list_2
:
indices = [list_2.index(l) if l in list_2 else None for l in list_1]
I set None
when an element is not present in your list_2
but you can put whatever value you desire.
Then, you form the dataframe:
df = pd.DataFrame({'Number': list_1, 'Index': indices})
Output:
Number Index
0 1 10.0
1 2 9.0
2 3 8.0
3 4 7.0
4 5 6.0
5 6 5.0
6 7 NaN
7 8 4.0
8 9 3.0
9 10 2.0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.