【问题标题】:How to do I count the number of string combinations in each row of a pandas dataframe?如何计算熊猫数据框每行中字符串组合的数量?
【发布时间】: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


【解决方案1】:

用途:

df1 = df.melt('id', value_name='method_').query("method_ != ''")

df = (df1.merge(df1, on='id', suffixes=('A','B'))
          .query("method_A != method_B")
          .groupby(['method_A','method_B'])
          .size()
          .reset_index(name='Number of Times Combined'))
print (df.head(20))
   method_A method_B  Number of Times Combined
0       AUC       HR                         1
1       AUC      PEP                         1
2       AUC       SC                         1
3       AUC       ST                         1
4       EEG       ET                         1
5       EEG       HR                         1
6       EEG       SC                         1
7        ET      EEG                         1
8        ET       HR                         1
9        ET       SC                         1
10       HR      AUC                         1
11       HR      EEG                         1
12       HR       ET                         1
13       HR      PEP                         2
14       HR       SC                         3
15       HR       ST                         1
16       HR    q-IEQ                         1
17       HR    q-SUS                         1
18      PEP      AUC                         1
19      PEP       HR                         2
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    • 2022-12-17
    • 2018-08-20
    • 2020-12-24
    • 1970-01-01
    • 2018-12-07
    相关资源
    最近更新 更多