Считая, сколько раз используется базовая функция, Python - PullRequest
0 голосов
/ 01 апреля 2020

Я хочу иметь возможность подсчитать, сколько раз функция полосы, а также сколько пробелов удаляется в течение l oop:

Воспроизводимый пример:

df = pd.DataFrame({'words': ['hi', 'thanks ', 'for ', 'helping '],
                   'more_words': ['i ', ' have', 'been', 'stuck'],
                   'even_more_words': ['four ', ' ages', 'word' , 'more words']})

count = 0 
# striping white spaces
for col in df.columns:
        df[col] = df[col].str.strip()

print("I stripped this many blank spaces:", count)

Вывод должен быть 7, так как он чередуется с 7 пробелами

Какой самый простой способ добиться этого? Будем очень благодарны за любые подсказки или области для изучения.

Ответы [ 2 ]

1 голос
/ 01 апреля 2020

Используя функцию .apply, вы можете обрезать и считать все значения одновременно, используя pandas.

import pandas as pd 

df = pd.DataFrame({'words': ['hi', 'thanks ', 'for ', ' helping '],
                   'more_words': ['i ', ' have', 'been', 'stuck'],
                   'even_more_words': ['four ', ' ages', 'word' , 'more words']})

count = 0 
# striping white spaces

def count_strip(string):
    global count

    striped_string = string.strip()
    count+= len(string) - len(striped_string)

    return striped_string

for col in df.columns:
        df[col] = df[col].apply(count_strip)

print("I striped this many blank spaces:", count)

output

I striped this many blank spaces: 8

1 голос
/ 01 апреля 2020

Самый простой способ - сохранить исходную длину строки, а затем вычесть из нее новую длину. Единственная мутация - операция strip, так что это должно быть правильно.

df = {'words': ['hi', 'thanks ', 'for ', 'helping '],
                   'more_words': ['i ', ' have', 'been', 'stuck'],
                   'even_more_words': ['four ', ' ages', 'word' , 'more words']}

count = 0 
# stripping white spaces
for col in df:
    count += sum(len(x) for x in df[col])
    df[col] = [x.strip() for x in df[col]]
    count -= sum(len(x) for x in df[col])
print("I stripped this many blank spaces:", count)

Это более минимальный пример, без использования Pandas, но идея та же.

...