且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按列表顺序从列表中选择 pandas 数据框的行

更新时间:2023-01-31 16:37:18

一种克服此问题的方法是将'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?