pandas中的str使用方法

在 Pandas 中,str 访问器用于对 SeriesDataFrame 中的字符串 数据进行矢量化 操作,使其能够像 Python 的字符串方法一样被调用,但支持对整个列或 Series 进行高效处理。

str 只能用于包含字符串类型的 SeriesDataFramestring 类型列。如果列的类型不是字符串,需要先转换:

python 复制代码
df['A'] = df['A'].astype(str)

然后,就可以使用 .str 进行字符串操作。

  • df['A'].str.upper()
  • df['A'].str.startswitch('a')

Pandas 的 .str 访问器不会在字符串操作后自动保持 Series 类型 ,而是可能返回 普通 Python 对象 (如 str)。如果不在每次字符串操作前显式使用 .str 访问器,就会导致后续的方法调用失败。

例如,users["name"].str[1:].str.lower() 是正确的,而 users["name"].str[1:].lower() 则不正确,因为它缺少.lower()方法之前的第二个 .str 访问器。

1667. 修复表中的名字 - 力扣(LeetCode)

编写解决方案,修复名字,使得只有第一个字符是大写的,其余都是小写的。

python 复制代码
import pandas as pd

def fix_names(users: pd.DataFrame) -> pd.DataFrame:
    users['name'] = users['name'].str[0].str.upper() + users['name'].str[1:].str.lower()
    return users.sort_values(by='user_id')
    
相关推荐
CodeCraft Studio1 天前
Excel处理控件Aspose.Cells教程:使用 Python 将 Pandas DataFrame 转换为 Excel
python·json·excel·pandas·csv·aspose·dataframe
njxiejing1 天前
Pandas数据结构(DataFrame,字典赋值)
数据结构·人工智能·pandas
Calihen的学习日志2 天前
【Pandas】3.1-数据预处理:列的基本操作
python·pandas
Source.Liu3 天前
【Python自动化】 21.2 Pandas 读取 Excel 时的 dtype 参数完全指南
python·自动化·pandas
Source.Liu3 天前
【Python自动化】 21 Pandas Excel 操作完整指南
python·excel·pandas
Source.Liu3 天前
【Python自动化】 21.1 Pandas 读取 Excel 文件的完整指南
python·自动化·pandas
偷心伊普西隆5 天前
Pandas DataFrame 指南
python·数据分析·pandas
chad__chang11 天前
Pandas的数据结构
数据结构·pandas
老歌老听老掉牙13 天前
Pandas DataFrame 列数操作完全指南
python·pandas
万粉变现经纪人13 天前
如何解决pip安装报错ModuleNotFoundError: No module named ‘websockets’问题
ide·pycharm·beautifulsoup·pandas·fastapi·pip·httpx