熊猫计算多列中的匹配项

时间:2020-09-13 14:30:20

标签: python pandas iterator comparison

我有一个数据框,其中包含<iframe src="https://drive.google.com/file/d/1gAQsX0hpAyH_iSbUXkyO87a8NpXscLEL/preview" width="640" height="480"></iframe>中的列。值为A - Z。 我需要迭代比较列0,1 or NAANA,依此类推,直到O,然后循环返回以与{{ 1}}和ZBN,然后再次从B开始。我只需要比较两列中O出现的行数。 我该怎么做?

1 个答案:

答案 0 :(得分:0)

使用SQL使设置操作更容易,因此下面的示例使用pandasql进行您要求的比较:

if(80.0 <= average && average <= 100)

其末尾打印如下:

import pandas as pd
import pandasql as ps
import string

# Create a string consisting of the letters in the English alphabet in alphabetical order
alphabet_string = string.ascii_uppercase

#print(alphabet_string)


# Create a list of data
data = []


# To approximate your data, use the value 0, 1, and None (~null) for each column
data.append([0] * len(alphabet_string))
data.append([1] * len(alphabet_string))
data.append([None] * len(alphabet_string))


# Create the pandas DataFrame  
df = pd.DataFrame(data, columns = [letter for letter in alphabet_string]) 


# Create a list of the letters from A to N
a_to_n = [letter for letter in alphabet_string if letter < "O"]

print(a_to_n)

# And N to O
n_to_o = [letter for letter in alphabet_string if letter > "M"]

print(n_to_o)

# Then perform the comparison in a nested loop over the two lists
for ll in a_to_n:
    for rl in n_to_o:
        cnt = ps.sqldf(f"select count(*) cnt from df where {ll} = 1 and {rl} = 1")["cnt"].iloc[0]
        print(f"Comparing {ll} to {rl}, there were {cnt} rows where the values matched.")