【发布时间】:2021-04-19 17:31:21
【问题描述】:
我有一个包含大量列的 pandas 数据框,我想生成满足特定条件的列的成对计数。给定这样的数据框:
df = pd.DataFrame({'A':['foo','foo','bar','bar'],
'B':['foo','foo','foo','bar'],
'C':['foo','bar','foo','bar'],
'D':['foo','foo','foo','foo'],
'E':['bar','bar','bar','bar']})
我想创建一个函数来告诉我,例如,对于每个列组合,两列都是“foo”的行数。我可以用这样的循环方法来做到这一点:
def pairwise_crit_count(df,crit):
# define column list
col_list = df.columns
# initialize dict that will turn into a pd frame for the result
result_dict = {'row':col_list}
for first_col in col_list:
# create empty list that will become the column of result
temp_list = []
for second_col in col_list:
# count the number of rows that meet the criteria
num = df.loc[(df[first_col]==crit) & (df[second_col]==crit)].shape[0]
temp_list.append(num)
# add to result dict
result_dict[first_col] = temp_list
return pd.DataFrame(result_dict)
pairwise_crit_count(df,'foo')
但我觉得我缺少一个更清洁的解决方案。
【问题讨论】: