Skip to main content
 首页 » 编程设计

python之如何为其中一列包含标点符号、空格的数据集编写代码并删除相应的行

2024年11月24日8qq号

我正在尝试清理包含一些汉字的数据集,并删除那些包含汉字的行。

我首先尝试用空格替换汉字,然后尝试使用正则表达式只用那些没有空格和标点符号的行和列填充数据集。

        df["reviewer_name"] = df["reviewer_name"].str.replace(r'[^\x00-\x7F]+','') 
        df['comments'] = df['comments'].str.replace(r'[^\x00-\x7F]+', '') 
        df = df[df['comments'].str.contains(r'\W+', na=False)] 
        df 

数据是这样的——

  • 数据-
    title_id 日期 Reviewer_name 评论

    258716 2019-04-21 Heap Chuan 新公寓,很干净,还有管理人员接待

-预期- 所有带有中文字符的行都将从数据集中消失

请您参考如下方法:

查找包含正则表达式的行:rows_to_drop是包含中文的行的索引。

rows_to_drop1= df.loc[df["reviewer_name"].str.contains(r'[^\x00-\x7F]', na=False)].index 
clean_df = df.drop(rows_to_drop1,axis=0) 
rows_to_drop2= df.loc[df["comments"].str.contains(r'[^\x00-\x7F]', na=False)].index 

现在您想通过删除 rows_to_drop2 来更新 clean_df,因此设置 inplace=True:

clean_df.drop(rows_to_drop2,axis=0,inplace=True) 

您也可以一次完成所有操作:

condition1 = df["reviewer_name"].str.contains(r'[^\x00-\x7F]', na=False) 
condition2 = df["comments"].str.contains(r'[^\x00-\x7F]', na=False) 
row_to_drop = df.loc[condition1 & condition2 ].index 
clean_df = df.drop(rows_to_drop,axis=0)