Python 如何通过任意长度的两列列表来子集dataframe
我尝试过布尔数组和.isin结构的不同组合,但我的能力不够 如果我有以下示例数据帧:Python 如何通过任意长度的两列列表来子集dataframe,python,pandas,Python,Pandas,我尝试过布尔数组和.isin结构的不同组合,但我的能力不够 如果我有以下示例数据帧: In[1]: import pandas as pd exampledf = pd.DataFrame({ 'factor1' : ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'], 'factor2' : ['e', 'e', 'e', 'e', 'f', 'f', 'f', 'f'],
In[1]: import pandas as pd
exampledf = pd.DataFrame({ 'factor1' : ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'],
'factor2' : ['e', 'e', 'e', 'e', 'f', 'f', 'f', 'f'],
'numeric' : [1., 2., 3., 4., 5., 6., 7., 8.] })
我需要传递任意长度的factor1、factor2对的列表,以返回包含这些因子组合的数据帧的子集
例如:
In[2]: def factorfilter(df, factorlist):
# code goes here
# returns a dataframe
factorfilter(exampledf, [['a', 'e'], ['c', 'f']])
Out[2]: factor1 factor2 numeric
0 a e 1
6 f f 7
(如果有比列表更好的设置方法,我洗耳恭听,这正是我想到的,并且很容易生成并传递给函数)。您可以使用多索引(索引多个列)。我想到了两种从示例模式构建索引的方法
import pandas as pd
index = pd.MultiIndex.from_product([list('abcd'),list('ef')],
names=['factor1','factor2'])
或
由此,您可以通过以下方式创建多索引数据帧
numerics = list(range(1,9))
df = pd.DataFrame({'numeric': numerics}, index=index)
测向输出
然后,通过将元组列表传递给ix属性,可以检索索引的子集
subdf = df.ix[[('a','e'), ('c','f')]]
子DF输出
你想要的输出中的第一个“f”是打字错误吗?确实是;我很抱歉,多重索引是我所需要的概念,但我没有想到;非常感谢。我实现的解决方案是以我的exampledf为例,创建一个多索引:exampledf.set_index(['factor1','factor2'],inplace=True,drop=True),然后我就可以按照您的建议调用exampledf.ix了。再次感谢。
numeric
factor1 factor2
a e 1
f 2
b e 3
f 4
c e 5
f 6
d e 7
f 8
[8 rows x 1 columns]
subdf = df.ix[[('a','e'), ('c','f')]]
numeric
factor1 factor2
a e 1
c f 6
[2 rows x 1 columns]