简体   繁体   English

按列名作为变量查询数据框

[英]Query dataframe by column name as a variable

I know this question has already been asked here , but my question a bit different.我知道这里已经有人问这个问题,但我的问题有点不同。 Lets say I have following df:假设我有以下 df:

import pandas as pd

df = pd.DataFrame({'A': ('a', 'b', 'c', 'd', 'e', 'a', 'b'), 'B': ('a', 'a', 'g', 'l', 'e', 'a', 'b'), 'C': ('b', 'b', 'g', 'a', 'e', 'a', 'b')})

myList = ['a', 'e', 'b']

I use this line to count the total number of occurrence of each elements of myList in my df columns:我使用这一行来计算我的 df 列中 myList 的每个元素的总出现次数:

print(df.query('A in @myList ').A.count())
5

Now, I am trying to execute the same thing by looping through columns names.现在,我试图通过循环列名来执行相同的操作。 Something like this:像这样的东西:

for col in df.columns:
    print(df.query('col in @myList ').col.count())

Also, I was wondering if using query for this is the most efficient way?另外,我想知道使用查询是否是最有效的方法? Thanks for the help.谢谢您的帮助。

Use this :用这个 :

df.isin(myList).sum()

A    5
B    5
C    6
dtype: int64

It checks every cell in the dataframe through myList and returns True or False.它通过 myList 检查数据框中的每个单元格并返回 True 或 False。 Sum uses the 1 or 0 reference and gets the total for each column Sum 使用 1 或 0 引用并获取每列的总数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM