You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何查找含特定字符的观测值并删除?附字母数字字符串场景

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 in Name
  • substr(..., 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 -1 refers 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 the Name column
  • 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 the Name variable
  • substr(Name, length(Name)) extracts the final character
  • ne '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:

  1. Extract the last character of each string in the Name column
  2. Keep only the rows where that character is not equal to "4"

内容的提问来源于stack exchange,提问作者Amin Karimi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:38:30