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

如何用Lambda函数移除DataFrame文本首尾换行符并新增列

移除字符串首尾换行符的解决方案

问题说明

你有一个包含带首尾换行符文本的DataFrame,希望用lambda函数精准移除每个字符串仅首尾的换行符,将结果保存为新列(不替换原列),同时保留字符串中间的换行符。

原始DataFrame代码

import pandas as pd

data = [
    "\n mark has \n no name",
    "\n john walks his \n dog",
    "mary is fun \n",
    "tim is \n old"
]

df = pd.DataFrame(data, columns=['Sentences'])

期望输出

处理后的新列内容如下:

"mark has \n no name",
"john walks his \n dog",
"mary is fun",
"tim is \n old"

实现代码

直接用apply结合lambda函数,调用字符串的strip('\n')方法即可——这个方法只会移除字符串开头和结尾的指定字符(这里是换行符\n),不会影响中间的内容:

# 添加处理后的新列
df['Cleaned_Sentences'] = df['Sentences'].apply(lambda x: x.strip('\n'))

# 查看结果
print(df)

运行后你会得到包含原列Sentences和新列Cleaned_Sentences的DataFrame,新列完全符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 11:55:26