Python 熊猫:选择行-基于列表-带重复行标签的DF
与此类似但不相同: 我有两个dfs:Python 熊猫:选择行-基于列表-带重复行标签的DF,python,pandas,indexing,filter,dataframe,Python,Pandas,Indexing,Filter,Dataframe,与此类似但不相同: 我有两个dfs: df1 = pd.DataFrame({'total': [25, 45, 75, 36, 45]}, index=['base', 'c', 'd', 'base', 'e']) total base 25 c 45 d 75 base 36 e 45 df2 = pd.DataFrame({'type': ['rc', 'rc', 'c%',
df1 = pd.DataFrame({'total': [25, 45, 75, 36, 45]},
index=['base', 'c', 'd', 'base', 'e'])
total
base 25
c 45
d 75
base 36
e 45
df2 = pd.DataFrame({'type': ['rc', 'rc', 'c%', 'c%', 'pp%']},
index=['base', 'c', 'd', 'base', 'e'])
type
base rc
c rc
d c%
base c%
e pp%
我想从df1中获取df2中值为“c%”和/或“pp%”的行
这就是我的做法
keep = df2[df2['type'].isin(['c%', 'pp%'])].index
Index([u'd', u'base', u'e'], dtype='object')
df1.loc[keep]
total
d 75
base 25
base 36
e 45
“base 25”不应该在那里,但因为我使用了标签,所以我理解它为什么在那里
预期结果:
total
d 75
base 36
e 45
如何更改代码以处理此问题 这就是你想要的吗
In [9]:
(df2['type'] == 'c%') | (df2['type'] == 'pp%')
Out[9]:
base False
c False
d True
base True
e True
Name: type, dtype: bool
In [8]:
df1[(df2['type'] == 'c%') | (df2['type'] == 'pp%')]
Out[8]:
total
d 75
base 36
e 45
In [54]: df1[['total']][df2['bool']=='True']
Out[54]:
total
d 75
base 36
e 45
重置索引怎么样?由于筛选可能不基于布尔值。是否要基于
true
或false
值或基于索引进行切片。抱歉,正确和错误只是一个例子,更容易解释。你提到的我想从df1中的df2中获得“正确”的行,实际上我无法理解你的问题我已经更新了我的问题,希望能更清楚一点。使用真与假不是一个好主意。