считая строки в строках - PullRequest
       24

считая строки в строках

2 голосов
/ 25 апреля 2019

У меня есть массив, который выглядит так:

a = ['UCI_99648;102568',  'UCI_99648;102568',  'UCI_99648;102568;99651', 'UCI_99651', 'UCI_99652', 'SIB_99658;102568;506010;706080', NaN]

Я хочу узнать, сколько укусов имеют одно число, например UCI_99651, UCI_99652

Итак, ожидаемый результат равен 2.

Как я могу сделать это в Python.

ПРИМЕЧАНИЕ: мои фактические данные очень велики, и числа могут быть любыми и, как указано в примере, могут включать пропущенные значения.

Ответы [ 5 ]

4 голосов
/ 25 апреля 2019

Предполагая, что структура всех строк соответствует структуре приведенного выше примера, будет реализовано следующее понимание списка:

l = ['UCI_99648;102568',  'UCI_99648;102568',  'UCI_99648;102568;99651', 
     'UCI_99651', 'UCI_99652', 'SIB_99658;102568;506010;706080', 'NaN']

[i for i in l if ';' not in i and i != 'NaN']

Вывод

['UCI_99651', 'UCI_99652']
2 голосов
/ 25 апреля 2019

Вы можете попробовать, как показано ниже. Надеюсь, что это решит вашу проблему.

p = [word.split(";")[0] for word in uci if word != 'NaN']
print(Counter(p))
#Counter({'UCI_99648': 3, 'UCI_99651': 1, 'UCI_99652': 1, 'SIB_99658': 1})
#To filter only one occurance you can try below.
b = [word for word in p if p.count(word)==1]
print(b)

Более подробную информацию вы можете получить здесь.

2 голосов
/ 25 апреля 2019

Поскольку вы пометили панд, другим способом:

s=pd.Series(a).dropna()
s[s.str.split(';').str.len().eq(1)]

3    UCI_99651
4    UCI_99652
0 голосов
/ 25 апреля 2019

Вы можете извлечь числа с помощью регулярных выражений. Например, что-то вроде этого:

import re
import numpy as np
from collections import Counter


def count_strings_with_unq_nums(list_of_strings):

    # Initialize two lists - one to keep track of where the numbers occur and another to isolate unique occurences of numbers
    all_nums_nested = []
    all_nums_flat = []

    # Loop through all strings and extract integers within
    for s in list_of_strings:
        try:
            nums = re.findall(r'\d+', s)
            all_nums_nested.append(nums)
            all_nums_flat.extend(nums)
        except:
            continue

    # Count occurences of all extracted numbers
    num_counter = Counter(all_nums_flat)

    # Loop through nested list to find strings where unique numbers occur
    unq_items = []
    for key, val in num_counter.items():
        if val == 1:
            for n, num_list in enumerate(all_nums_nested):
                if key in num_list:
                    unq_items.append(list_of_strings[n])

    # Return the number of strings containing unique numbers.        
    return len(set(unq_items))

if __name__ == '__main__':
    a = ['UCI_99648;102568',  'UCI_99648;102568',  'UCI_99648;102568;99651', 'UCI_99651', 'UCI_99652', 'SIB_99658;102568;506010;706080', np.NaN]

    print(count_strings_with_unq_nums(a))

>>> 2
0 голосов
/ 25 апреля 2019

При необходимости выполните проверку на наличие NaN, используя numpy или pandas.

a = ['UCI_99648;102568',  'UCI_99648;102568',  'UCI_99648;102568;99651', 'UCI_99651', 'UCI_99652', 'SIB_99658;102568;506010;706080', 'NaN']


b = [i.split(';')[0] for i in a if i != 'NaN' and i.startswith('UCI_')]

b = [x for x in b if b.count(x)==1]

print(b)

#[UCI_99651, UCI_99652]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...