如何计算熊猫列中的特殊字符?

时间:2020-01-10 19:07:23

标签: python pandas dataframe

我正在尝试使用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

如何继续进行下去?

2 个答案:

答案 0 :(得分:2)

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

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

如果您在数据框上使用Apply,则必须访问所需的列,并告诉apply遍历如下行:

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

答案 1 :(得分:1)

让我们尝试使用np.where而不是循环:

import string
df['new']=np.where(~df['str'].str.contains('|'.join(list(string.ascii_letters)))
                   ,df['str'].str.len(),np.nan)
print(df)

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