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

时间:2018-08-21 07:50:51

标签: python pandas dataframe

该问题最初是作为问题here提出的,但由于该问题被标记为重复,因此无法获得正确答案。

对于给定的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')从列表中选择行

例如

# from
list_of_values = [3,4,6]

# we would like, as a result
#      A   B
# 2    3   3
# 3    4   5
# 1    6   2

使用here中提到的isin并不令人满意,因为它不能保持'A'值的输入列表中的顺序。

如何实现上述目标?

3 个答案:

答案 0 :(得分:3)

克服此问题的一种方法是将'A'列设为index,并在新生成的loc上使用pandas.DataFrame。最终,可以重置欠采样数据帧的索引。

方法如下:

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 

请注意,此方法的缺点是原始索引已在该过程中丢失。

有关pandas索引的更多信息:What is the point of indexing in pandas?

答案 1 :(得分:2)

merge与列表创建的助手DataFrame一起使用,并且其列名与匹配的列相同:

df = pd.DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3,5]})

list_of_values = [3,6,4]
df1 = pd.DataFrame({'A':list_of_values}).merge(df)
print (df1)
   A  B
0  3  3
1  6  2
2  4  5

有关更一般的解决方案:

df = pd.DataFrame({'A' : [5,6,5,3,4,4,6,5], 'B':range(8)})
print (df)
   A  B
0  5  0
1  6  1
2  5  2
3  3  3
4  4  4
5  4  5
6  6  6
7  5  7

list_of_values = [6,4,3,7,7,4]

#create df from list 
list_df = pd.DataFrame({'A':list_of_values})
print (list_df)
   A
0  6
1  4
2  3
3  7
4  7
5  4

#column for original index values
df1 = df.reset_index()
#helper column for count duplicates values
df1['g'] = df1.groupby('A').cumcount()
list_df['g'] = list_df.groupby('A').cumcount()

#merge together, create index from column and remove g column
df = list_df.merge(df1).set_index('index').rename_axis(None).drop('g', axis=1)
print (df)
   A  B
1  6  1
4  4  4
3  3  3
5  4  5

答案 2 :(得分:1)

1] list_of_values的通用方法。

In [936]: dff = df[df.A.isin(list_of_values)]

In [937]: dff.reindex(dff.A.map({x: i for i, x in enumerate(list_of_values)}).sort_values().index)
Out[937]:
   A  B
2  3  3
3  4  5
1  6  2

2] 如果对list_of_values进行了排序。您可以使用

In [926]: df[df.A.isin(list_of_values)].sort_values(by='A')
Out[926]:
   A  B
2  3  3
3  4  5
1  6  2
相关问题