在尝试根据自定义列表重新排列列时,我遇到了一个问题。例如:我的dataframe示例是:
test_df = pd.DataFrame({'ID':[1,2,3,4,5],'Country Code':['US','DE','SE','CH','AT']})
test_df

我的名单是:
list_country_code = ['DE','SE','AT','UK']现在,我想要的是数据应该按照列表中指定的顺序重新排列。因此,所需的输出是:

正如您在这里看到的,dataframe的Country Code列是按照列表的顺序重新排列的。可能发生的情况是,任何元素都存在于列表中,而不是列中,反之亦然,在这种情况下,我们只需将其放在dataframe的末尾即可。
我尝试过使用sort_values()来使用这个列表,但到目前为止没有任何进展。我怎样才能继续这样做呢?
发布于 2022-03-20 17:52:34
您可以使用pd.merge来完成此操作。
list_country_code = ['DE','SE','AT','US']
list_country_code = pd.DataFrame(list_country_code, columns = ["Country Code"])
pd.merge(list_country_code, test_df, on = "Country Code", how = "outer")这会返回
Country Code ID
0 DE 2
1 SE 3
2 AT 5
3 US 1
4 CH 4发布于 2022-03-20 17:04:00
创建一个中间系列,用作自定义排序键:
s = pd.Series(range(len(list_country_code)), index=list_country_code)
out = test_df.sort_values('Country Code', key=lambda x: x.map(s))
print(out)
# Output
ID Country Code
1 2 DE
2 3 SE
4 5 AT
0 1 US
3 4 CHhttps://stackoverflow.com/questions/71548774
复制相似问题