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

在Pandas中按长度获取字符串列最大值并赋值给全列

Pandas替换列值为最长字符串的实现

直接上代码和实操说明:

import pandas as pd

# 模拟你的原始数据
df = pd.DataFrame({'currency': ['CNY', 'CNY,INR', 'INR']})

# 步骤1:定位列中长度最长的字符串
# 先计算每个元素的长度,取长度最大值对应的行索引,再取出对应字符串
max_len_curr = df.loc[df['currency'].str.len().idxmax(), 'currency']

# 步骤2:将整个currency列替换为该最长值
df['currency'] = max_len_curr

执行后得到的结果如下:

currency
CNY,INR
CNY,INR
CNY,INR

额外补充

如果列中存在多个长度相同的最长字符串,idxmax()会返回第一个出现的字符串索引。若需要取最后一个最长字符串,可以用以下代码:

max_len = df['currency'].str.len().max()
max_len_curr = df[df['currency'].str.len() == max_len]['currency'].iloc[-1]

再将该值赋值给整个列即可,可根据实际需求选择对应方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 10:30:29