【发布时间】:2022-07-21 18:14:52
【问题描述】:
我正在尝试计算字符串组合出现在数据帧的每一行中的次数。每个 ID 使用多种方法(有些 ID 使用的方法比其他方法多),我想计算任意两种方法组合在一起的次数。
# df is from csv and has blank cells - I've used empty strings to demo here
df = pd.DataFrame({'id': ['101', '102', '103', '104'],
'method_1': ['HR', 'q-SUS', 'PEP', 'ET'],
'method_2': ['q-SUS', 'q-IEQ', 'AUC', 'EEG'],
'method_3': ['SC', '', 'HR', 'SC'],
'method_4': ['q-IEQ', '', 'ST', 'HR'],
'method_5': ['PEP', '', 'SC', '']})
print(df)
id method_1 method_2 method_3 method_4 method_5
0 101 HR q-SUS SC q-IEQ PEP
1 102 q-SUS q-IEQ
2 103 PEP AUC HR ST SC
3 104 ET EEG SC HR
我想最终得到一个看起来像这样的表格: |方法A |方法 B |合并次数| | :--------: | :--------: | :------------------------: | |人力资源 | SC | 3 | |人力资源 | q-SUS | 1 | |人力资源 |政治人物 | 2 | | q-IEQ | q-SUS | 2 | |脑电图 |东部时间 | 1 | |脑电图 | SC | 1 | |等|等|等等|
到目前为止,我一直在尝试使用 itertools.combinations 和 collections Counter 对这段代码进行变体:
import numpy as np
import pandas as pd
import itertools
from collections import Counter
def get_all_combinations_without_nan(row):
# remove nan - this is for the blank csv cells
set_without_nan = {value for value in row if isinstance(value, str)}
# generate all combinations of values in row
all_combinations = []
for index, row in df.iterrows():
result = list(itertools.combinations(set_without_nan, 2))
all_combinations.extend(result)
return all_combinations
# get all possible combinations of values in a row
all_rows = df.apply(get_all_combinations_without_nan, 1).values
all_rows_flatten = list(itertools.chain.from_iterable(all_rows))
count_combinations = Counter(all_rows_flatten)
print(count_combinations)
它正在做某事,但它似乎在计算多次或某事(它计算的组合比实际存在的更多。我在 Stack 上看得很清楚,但似乎无法解决这个问题 - 一切似乎都很接近不过!
希望有人能提供帮助 - 谢谢!
【问题讨论】:
-
仅查看您的代码,您正在为所有值添加所有组合 -> 这将导致您计算所有组合两次。您可能希望从结果列表中删除重复项。
标签: python pandas dataframe itertools