按列表顺序从列表中选择 pandas 数据框的行 [英] Select rows of pandas dataframe from list, in order of list
问题描述
The question was originally asked here as a comment but could not get a proper answer as the question was marked as a duplicate.
对于给定的pandas.DataFrame
,让我们说
df = DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3, 5]})
df
A B
0 5 1
1 6 2
2 3 3
3 4 5
我们如何基于列中的值(例如,'A'
)从列表中选择行
How can we select rows from a list, based on values in a column ('A'
for instance)
例如
# from
list_of_values = [3,4,6]
# we would like, as a result
# A B
# 2 3 3
# 3 4 5
# 1 6 2
使用提及的isin
here 不能令人满意,因为它没有保持'A'
值输入列表的顺序.
Using isin
as mentioned here is not satisfactory as it does not keep order from the input list of 'A'
values.
如何实现上述目标?
推荐答案
一种克服此问题的方法是将'A'
列设置为index
,并在新生成的pandas.DataFrame
上使用loc
.最终,可以重置欠采样数据帧的索引.
One way to overcome this is to make the 'A'
column an index
and use loc
on the newly generated pandas.DataFrame
. Eventually, the subsampled dataframe's index can be reset.
方法如下:
ret = df.set_index('A').loc[list_of_values].reset_index(inplace=False)
# ret is
# A B
# 0 3 3
# 1 4 5
# 2 6 2
请注意,此方法的缺点是在此过程中丢失了原始索引.
Note that the drawback of this method is that the original indexing has been lost in the process.
关于pandas
索引的更多信息:索引的意义是什么在熊猫里?
More on pandas
indexing: What is the point of indexing in pandas?
这篇关于按列表顺序从列表中选择 pandas 数据框的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!