计算一列中有多少个单元格被条纹化

To count how many cells are striped in a column

aw_data = {'first_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], 
        'last_name': [" 'Miller' "," 'Jacobson' ", 'Ali', 'Milner', 'Cooze'], 
        'age': [42, 52, 36, 24, 73], 
        'preTestScore': [4, 24, 31, 2, 3],
        'postTestScore': [25, 94, 57, 62, 70]}
df = pd.DataFrame(raw_data, columns = ['first_name', 'last_name', 'age', 'preTestScore', 'postTestScore'])
df

我的任务是首先删除姓氏列中的引号,然后计算该列中有多少单元格在此过程中被删除。

我的作品: 我可以去掉姓氏列中的引号,但我怎么算呢。 我正在使用:

df["last_name"]=df["last_name"].apply(lambda x: x.replace("'",""))

我的输出应该是'two'。 感谢任何帮助。

你可以试试下面的-

df[df["last_name"].str.contains("'")].count()["last_name"]

count how many cells in that column were stripped in the process

您可以使用:

df['last_name'].str.split("'").str[1:-1].str.len().ne(0).sum()

要了解我的评论与此评论之间的区别,请考虑以下示例:

raw_data = {'first_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], 
    'last_name': [" 'Miller's' "," 'Jacobson's' ", 'Ali', 'Milner', "Cooze's"], 
    'age': [42, 52, 36, 24, 73], 
    'preTestScore': [4, 24, 31, 2, 3],
    'postTestScore': [25, 94, 57, 62, 70]}
df = pd.DataFrame(raw_data, columns = 
    ['first_name', 'last_name', 'age', 'preTestScore', 'postTestScore'])
print(df)

  first_name       last_name  age  preTestScore  postTestScore
0      Jason     'Miller's'    42             4             25
1      Molly   'Jacobson's'    52            24             94
2       Tina             Ali   36            31             57
3       Jake          Milner   24             2             62
4        Amy         Cooze's   73             3             70

您可以使用:

df['last_name'].str.split("'").str[1:-1].str.len().ne(0).sum()
#2 since the last_name `Cooze's` contains an apostrophe but not quoted.

鉴于:

df['last_name'].str.contains("'").sum()
#3 since it counts all rows having an apostrophe

您可以尝试 str.findallsum

In [99]: df.last_name.str.findall(r"^ *\'|\' *$").astype(bool).sum()
Out[99]: 2

在修改后的样本 df 上:

  first_name        last_name  age  preTestScore  postTestScore
0      Jason        'Miller'    42             4             25
1      Molly       Jacobson'    52            24             94
2       Tina             Ali'   36            31             57
3       Jake         Milner's   24             2             62
4        Amy  Cooze             73             3             70

In [106]: df.last_name.str.findall(r"^ *\'|\' *$").astype(bool).sum()
Out[106]: 3