确定字符串中数字的计数和百分比(熊猫)
我在数据集 df 中有一个列,其中包含这样的字符串
Webs
https://www.mhouse.com/107462464135489/posts/please-lets-be-guidedun-is-where-the-code/142970213918047/
https://www.msed.com/IKONINIBWANASEEDMARCH2020.html
https://www.msed.com/
https://carrice.com/jen/stat/1241025420562178050?lang=en
...
我想确定其中的数量和百分比;所以,例如
Count Percentage
15 (and the percentage compared to the length of the string)
4 ...
0 ...
19 ...
如果我没有错,我会使用 is digit 的组合来确定字符串中的位数,使用 len() 来确定字符串的长度,然后是百分比。
回答
您可以使用Series.str.count正则表达式计算字符串中的位数。此外,您可以使用Series.str.len(). 一旦你这样做了,计算百分比就很简单了!
df["digit_count"] = df["Webs"].str.count("d")
df["total_characters"] = df["Webs"].str.len()
df["digit_percentage"] = df["digit_count"] / df["total_characters"] * 100
print(df)
Webs digit_count total_characters digit_percentage
0 https://www.mhouse.com/107462464135489/posts/p... 30 103 29.126214
1 https://www.msed.com/IKONINIBWANASEEDMARCH2020... 4 51 7.843137
2 https://www.msed.com/ 0 21 0.000000
3 https://carrice.com/jen/stat/12410254205621780... 19 56 33.928571