【问题标题】:Pandas count matches across multiple columns [closed]Pandas 计算多列中的匹配项[关闭]
【发布时间】:2020-09-13 14:30:20
【问题描述】:
我有一个数据框,其中包含来自A - Z 的列。值为0,1 or NA。
我需要迭代比较列A和N、A和O等直到Z,然后循环返回开始与B和N、B和的比较O,然后再次来自C。我只需要在被比较的两列中出现1 的行数。
我该如何做到这一点?
【问题讨论】:
标签:
python
pandas
iterator
comparison
【解决方案1】:
使用 SQL 可以更轻松地进行设置操作,因此下面的示例使用 pandasql 进行您要求的比较:
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.")
其中的结尾打印如下:
Comparing N to U, there were 1 rows where the values matched.
Comparing N to V, there were 1 rows where the values matched.
Comparing N to W, there were 1 rows where the values matched.
Comparing N to X, there were 1 rows where the values matched.
Comparing N to Y, there were 1 rows where the values matched.
Comparing N to Z, there were 1 rows where the values matched.