按列表过滤 pandas 数据框 [英] Filter pandas dataframe by list

查看:53
本文介绍了按列表过滤 pandas 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,该数据框的行名为"Hybridization REF".我希望进行过滤,以便仅获取标签与列表中项目之一具有相同标签的项目的数据.

I have a dataframe that has a row called "Hybridization REF". I would like to filter so that I only get the data for the items that have the same label as one of the items in my list.

基本上,我想执行以下操作:

Basically, I'd like to do the following:

dataframe[dataframe["Hybridization REF'].apply(lambda: x in list)] 

但该语法不正确.

推荐答案

使用重新索引更新

df.reindex(collist, axis=1)

df.reindex(rowlist, axis=0)

两者兼有:

df.reindex(index=rowlist, columns=collist)


您可以使用.loc或列过滤:


You can use .loc or column filtering:

df = pd.DataFrame(data=np.random.rand(5,5),columns=list('ABCDE'),index=list('abcde'))

df
          A         B         C         D         E
a  0.460537  0.174788  0.167554  0.298469  0.630961
b  0.728094  0.275326  0.405864  0.302588  0.624046
c  0.953253  0.682038  0.802147  0.105888  0.089966
d  0.122748  0.954955  0.766184  0.410876  0.527166
e  0.227185  0.449025  0.703912  0.617826  0.037297

collist = ['B','D','E']

rowlist = ['a','c']

获取列表中的列:

df[collist]

输出:

          B         D         E
a  0.174788  0.298469  0.630961
b  0.275326  0.302588  0.624046
c  0.682038  0.105888  0.089966
d  0.954955  0.410876  0.527166
e  0.449025  0.617826  0.037297

获取列表中的行

df.loc[rowlist]

          A         B         C         D         E
a  0.460537  0.174788  0.167554  0.298469  0.630961
c  0.953253  0.682038  0.802147  0.105888  0.089966

这篇关于按列表过滤 pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆