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')
    
相关推荐
景早1 天前
pandas简介
pandas
懒惰蜗牛4 天前
Day10:Python实现Excel自动汇总
python·numpy·pandas·pip·1024程序员节·python读写excel
CodeCraft Studio4 天前
国产化Excel开发组件Spire.XLS教程:在Python中将Pandas DataFrame导出到Excel的详细教程
python·excel·pandas
sunbyte6 天前
从零掌握 Pandas:数据分析的黄金钥匙|01:认识Pandas
数据挖掘·数据分析·pandas
是梦终空6 天前
计算机毕业设计240—基于python+爬虫+html的微博舆情数据可视化系统(源代码+数据库)
爬虫·python·pandas·课程设计·毕业论文·计算机毕业设计·微博舆情可视化
万粉变现经纪人9 天前
如何解决 pip install -r requirements.txt 私有索引未设为 trusted-host 导致拒绝 问题
开发语言·python·scrapy·flask·beautifulsoup·pandas·pip
万粉变现经纪人10 天前
如何解决 pip install -r requirements.txt 私有仓库认证失败 401 Unauthorized 问题
开发语言·python·scrapy·flask·beautifulsoup·pandas·pip
m***记11 天前
Python 数据分析入门:Pandas vs NumPy 全方位对比
python·数据分析·pandas
小钱c711 天前
Python使用 pandas操作Excel文件并新增列数据
python·excel·pandas
虎头金猫13 天前
我的远程开发革命:从环境配置噩梦到一键共享的蜕变
网络·python·网络协议·tcp/ip·beautifulsoup·负载均衡·pandas