Pandas 使用列上的索引和条件选择数据框

Pandas dataframe selecting with index and condition on a column

我正在尝试一段时间来解决这个问题:

我有这样的 daraframe:

import pandas as pd
df=pd.DataFrame(np.array([['A', 2, 3], ['B', 5, 6], ['C', 8, 9]]),columns=['a', 'b', 'c'])
j=[0,2]

但是当我尝试 select 仅通过索引列表和列上的条件过滤其中的一部分时,我得到错误...

df[df.loc[j]['a']=='A']

有些错误,但我不明白这里的问题是什么。你能帮帮我吗?

这是错误信息:

IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match).

过滤后的DataFrame和原来的比较,索引不一样,所以报错

您需要比较过滤后的 DataFrame:

df1 = df.loc[j]
print (df1)
   a  b  c
0  A  2  3
2  C  8  9

out = df1[df1['a']=='A']
print(out)
   a  b  c
0  A  2  3

您的解决方案可以通过 Series.reindex:

与原始索引转换过滤掩码的索引一起使用
out = df[(df.loc[j, 'a']=='A').reindex(df.index, fill_value=False)]
print(out)
   a  b  c
0  A  2  3

或更好的解决方案:

out = df[(df['a'] == 'A') & (df.index.isin(j))]
print(out)
   a  b  c
0  A  2  3

布尔数组和数据帧的长度应该相同。这里你的 df 长度是 3 但布尔数组 df.loc[j]['a']=='A' 长度是 2

你应该这样做:

>>> df.loc[j][df.loc[j]['a']=='A']
   a  b  c
0  A  2  3