如何查找含特定字符的观测值并删除?附字母数字字符串场景
Got it, let's figure out how to solve this problem! You need to remove rows where the last character of the Name column is '4'—here's how to do it in some of the most popular data analysis tools:
Solutions by Tool
R Language
You have two straightforward options here, depending on whether you prefer base R or the tidyverse ecosystem:
Base R Approach
Use substr() to extract the last character and filter rows:
# Assume your data frame is named df df_filtered <- df[substr(df$Name, nchar(df$Name), nchar(df$Name)) != "4", ]
nchar(df$Name)gets the length of each string inNamesubstr(..., nchar(...), nchar(...))pulls the final character of each string- The boolean index keeps only rows where that final character isn't "4"
Tidyverse (dplyr + stringr) Approach
This is more readable for most users:
library(dplyr) library(stringr) df_filtered <- df %>% filter(str_sub(Name, -1) != "4")
str_sub(Name, -1)is a quick way to grab the last character of a string (the-1refers to the position counting from the end)filter()keeps only rows that meet the condition
Python (Pandas)
Pandas makes this super concise with string indexing:
import pandas as pd # Assume your DataFrame is named df df_filtered = df[df['Name'].str[-1] != '4']
df['Name'].str[-1]accesses the last character of each string in theNamecolumn- The boolean mask filters out any rows where that character is "4"
If you have missing values in the Name column, add na=False to avoid errors:
df_filtered = df[df['Name'].str[-1] != '4', na=False]
SAS
Use the substr() function in a where clause to filter your dataset:
/* Assume your input dataset is named raw_data */ data filtered_data; set raw_data; where substr(Name, length(Name)) ne '4'; run;
length(Name)returns the length of each string in theNamevariablesubstr(Name, length(Name))extracts the final characterne '4'keeps only rows where that character is not "4"
Core Idea Across All Tools
No matter which tool you use, the logic is the same:
- Extract the last character of each string in the
Namecolumn - Keep only the rows where that character is not equal to "4"
内容的提问来源于stack exchange,提问作者Amin Karimi
相关产品推荐
相关产品推荐

