python - Pandas 数据帧 : selection of multiple elements in several columns

标签 python pandas dataframe multiple-columns selection

我有这个Python Pandas DataFrame DF:

DICT = {  'letter': ['A','B','C','A','B','C','A','B','C'],
          'number': [1,1,1,2,2,2,3,3,3],
          'word'  : ['one','two','three','three','two','one','two','one','three']}

DF = pd.DataFrame(DICT)

看起来像:

  letter  number   word
0      A       1    one
1      B       1    two
2      C       1  three
3      A       2  three
4      B       2    two
5      C       2    one
6      A       3    two
7      B       3    one
8      C       3  three

我想提取这些行

  letter  number   word
       A       1    one
       B       2    two
       C       3  three

首先我累了:

DF[(DF['letter'].isin(("A","B","C"))) & 
    DF['number'].isin((1,2,3))        &
    DF['word'].isin(('one','two','three'))]

当然不行,一切都已经选择了

然后我测试了:

Bool = DF[['letter','number','word']].isin(("A",1,"one"))
DF[np.all(Bool,axis=1)]

很好,有效!但仅限于一行... 如果我们采取下一步并向 .isin() 提供一个可迭代对象:

Bool = DF[['letter','number','word']].isin((("A",1,"one"),
                                            ("B",2,"two"),
                                            ("C",3,"three")))

然后就失败了, bool 数组满了False...

我做错了什么?是否有更优雅的方法来根据多个列进行此选择?

(无论如何,我想避免 for 循环,因为我使用的实际 DataFrame 非常大,所以我正在寻找最快的最佳方法来完成这项工作)

最佳答案

想法是使用所有三元组值创建新的DataFrame,然后 merge与原始DataFrame:

L = [("A",1,"one"),
     ("B",2,"two"),
     ("C",3,"three")]

df1 = pd.DataFrame(L, columns=['letter','number','word'])
print (df1)
  letter  number   word
0      A       1    one
1      B       2    two
2      C       3  three

df = DF.merge(df1)
print (df)
  letter  number   word
0      A       1    one
1      B       2    two
2      C       3  three

另一个想法是创建元组列表,转换为Series,然后按 isin 进行比较:

s = pd.Series(list(map(tuple, DF[['letter','number','word']].values.tolist())),index=DF.index)
df1 = DF[s.isin(L)]
print (df1)
  letter  number   word
0      A       1    one
4      B       2    two
8      C       3  three

关于python - Pandas 数据帧 : selection of multiple elements in several columns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53432043/

相关文章:

python - 将数据框列的匹配值与系列值相加

java - 在图像中查找图像

python - 将 UTF-8 字符串转换为 XML/HTML 字符串时出现问题

python - 防止一个函数连续被调用两次

pandas - Pandas 中不规则时间序列的rolling_sum?

python - 返回索引在 pandas 中有多于一行的 groupby 结果

python - 使用 Scipy 记录正态随机变量

python - 在 python 中使用 zip 函数迭代几列,给出错误

r - 如何将整个 data.frame 转换为数字

python - 在数据框中使用数组对列进行排序