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

Python pandas如何删除字符串中的换行符 现有解决方案失效求助

问题原因

你两次尝试的代码均存在用法错误:

  • 两次代码都同时使用了inplace=True参数和赋值操作:inplace=True会让方法直接修改原对象,返回值为None,将None赋值给Prescription_Drug_Name列会导致整列值被清空。
  • 直接调用Series的replace方法默认是全值匹配,只有单元格内容完全等于\n才会触发替换,无法替换字符串内部的换行符,需要调用str.replace处理字符串内部的子串。
解决方案

推荐使用无inplace的写法,逻辑更清晰易调试:

for df in df_list:
    df.columns = [c.replace(' ', '_') for c in df.columns]
    df.drop(df.columns.difference(['Prescription_Drug_Name','Drug_Tier', 'Drug_Notes']), 1, inplace=True)
    df.drop(df.tail(3).index, inplace=True)
    # 替换字符串内所有换行符,regex=False表示按普通字符串匹配,性能更高
    df['Prescription_Drug_Name'] = df['Prescription_Drug_Name'].str.replace('\n', '', regex=False)
    df_list_clean.append(df)

补充适配场景

如果你的Excel中同时存在Windows格式的换行符\r\n,可以用正则匹配一次性清除所有换行相关字符:

df['Prescription_Drug_Name'] = df['Prescription_Drug_Name'].str.replace(r'[\r\n]', '', regex=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 21:45:00