gpt4 book ai didi

python - 如何计算 Pandas 列中的特殊字符?

转载 作者:行者123 更新时间:2023-12-05 03:56:11 25 4
gpt4 key购买 nike

我正在尝试使用 Pandas 计算列中特殊字符的数量。但没有获得所需的输出。

我的 .txt 文件是:

str
Aa
Bb
?? ?
###

我的代码是:

import pandas as pd

df=pd.read_csv('inn.txt',sep='\t')

def count_special_char(string):
special_char = 0

for i in range(len(string)):
if(string[i].isalpha()):
continue
else:
special_char = special_char + 1

df["new"]=df.apply(count_special_char, axis = 0)
print(df)

输出是:

    str  new
0 Aa NaN
1 Bb NaN
2 ?? ? NaN
3 ### NaN

期望的输出是:

    str  new
0 Aa NaN
1 Bb NaN
2 ?? ? 4
3 ### 3

如何推进?

最佳答案

你可以像这样在一行中完成:

df["new"] = df["str"].apply(lambda p: sum( not p.isalpha() for q in p )))

如果你在数据框上使用应用,你必须访问你想要的列,并告诉 apply像这样遍历行:

df["new"] = df.apply(lambda p: sum( not q.isalpha() for q in p["str"] ), axis=1)

关于python - 如何计算 Pandas 列中的特殊字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59687650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com