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')
    
相关推荐
lzq60319 小时前
【Python实战】用Pandas轻松实现Excel数据清洗与可视化
python·excel·pandas
啊阿狸不会拉杆2 天前
第十五章:Python的Pandas库详解及常见用法
开发语言·python·数据分析·pandas
夜松云3 天前
Python数据可视化与数据处理全解析:Matplotlib图形控制与Pandas高效数据分析实战
python·算法·信息可视化·pandas·matplotlib
蹦蹦跳跳真可爱5893 天前
Python----数据分析(足球运动员数据分析)
python·数据挖掘·数据分析·pandas·matplotlib
liuweidong08024 天前
【Pandas】pandas Series to_xarray
linux·运维·pandas
王有品5 天前
python之size,count的区别
python·机器学习·pandas
慕丹5 天前
知识周汇 | 用 matplotlib 轻松绘制折线图、散点图、柱状图、直方图
python·pandas·matplotlib
杜子腾dd5 天前
21.Excel自动化:如何使用 xlwings 进行编程
运维·python·自动化·excel·numpy·pandas
这里有鱼汤6 天前
Pandas:从入门到精通,只需这一篇就够了!
后端·python·pandas
liuweidong08028 天前
【Pandas】pandas Series plot.line
信息可视化·数据分析·pandas