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

syl*_*ong 5 python dataframe pandas

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

对于给定的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
Run Code Online (Sandbox Code Playgroud)

我们如何基于列中的值从列表中选择行('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
Run Code Online (Sandbox Code Playgroud)

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

如何实现上述目标?

syl*_*ong 8

解决此问题的一种方法是使'A'列 anindexloc在新生成的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 
Run Code Online (Sandbox Code Playgroud)

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

有关pandas索引的更多信息:在Pandas 中索引有什么意义?


jez*_*ael 6

mergeDataFrame列表创建的帮助器以及匹配列的列名一起使用:

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
Run Code Online (Sandbox Code Playgroud)

对于更通用的解决方案:

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]
Run Code Online (Sandbox Code Playgroud)
#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
Run Code Online (Sandbox Code Playgroud)

  • 原始索引在此过程中丢失。 (2认同)