[英]Counting how many times a base function is being used, Python
我希望能够计算在 for 循环中删除了多少次 strip 函数以及删除了多少空格:
可重现的例子:
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 个空格
实现这一目标的最简单方法是什么? 任何要研究的提示或领域将不胜感激。
最简单的方法是存储原始字符串长度,然后从中减去新长度。 唯一的变化是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,但想法是相同的。
使用 .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)
输出
I striped this many blank spaces: 8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.