Question:个 我正在处理一个Python项目,其中有一个包含两列的数据集:"Big List"和"Small List".我的目标是将"小列表"列中的值与"大列表"列中的值进行比较,并相应地对它们进行排序.如果在"Big List"列中找到"Small List"列中的值,我希望对"Small List"列中的相应行进行排序.此外,如果在"Big List"列中找不到"Small List"列中的值,我想将其列在一个名为"Not Match to Big List"的新列中.
"大名单"中的值不是唯一的,但"小名单"中的值是唯一的.
下面是一个例子:
Big List | Small List |
---|---|
10 | 17 |
2 | 15 |
15 | 42 |
17 | 31 |
30 | 45 |
40 | 30 |
45 | |
47 | |
50 |
在本例中,我想将"Small List"列中的每个值与"Big List"列中的值进行比较.如果找到匹配项,我希望对"Small List"列中的相应行进行排序.如果没有找到匹配项,我想将该值列在"不匹配到大列表"列中.
预期结果:
Big List | Small List | Not Matched to Big List |
---|---|---|
10 | 31 | |
2 | 42 | |
15 | 15 | |
17 | 17 | |
30 | 30 | |
40 | ||
45 | 45 | |
47 | ||
50 |
当找到匹配项时如何对"Small List"列中的行进行排序,以及在没有匹配项时如何填充"Not Match to Big List"列,这让我苦苦思索.任何关于如何实现这一目标的帮助或建议都将受到高度赞赏!
以下是我到目前为止掌握的代码:
import pandas as pd
data = {'Big List': [10,2,15,17,30,40,45,47,50], 'Small List': [17,15,42,31,45,30]}
df = pd.DataFrame(data)
# Loop through rows and compare values
for index, row in df.iterrows():
if row['Small List'] in df['Big List']:
# Sort the row in the "Small List" column
# Stuck here
else:
# Add value to "Not Matched to Big List" column
# Stuck here
print(df)