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

如何将Pandas DataFrame中列值转换为列表并去除末尾逗号?

Pandas处理带尾随逗号的列转为列表形式

问题说明

现有Pandas DataFrame的df['fruits']列内容如下:

apple,
orange,
pineapple,
banana,tomato,
cabbage,watermelon,

Name: fruits, Length: 5, dtype: object

需要将该列的每个值转换为列表形式,同时去除每个值末尾的逗号,最终期望输出如下:

['apple']
['orange']
['pineapple']
['banana', 'tomato']
['cabbage', 'watermelon']

Name: fruits, Length: 5, dtype: object

解决方案

可以通过Pandas的字符串处理方法链式调用完成需求:

# 处理逻辑:先移除末尾逗号,再按逗号分割为列表
df['fruits'] = df['fruits'].str.rstrip(',').str.split(',')

步骤解释

  • str.rstrip(','):仅移除每个字符串末尾的逗号,保留中间用于分隔元素的逗号
  • str.split(','):将处理后的字符串按逗号分割,自动转换为列表类型

完整示例代码

import pandas as pd

# 模拟原始数据
data = {
    'fruits': [
        'apple,',
        'orange,',
        'pineapple,',
        'banana,tomato,',
        'cabbage,watermelon,'
    ]
}
df = pd.DataFrame(data)

# 执行处理
df['fruits'] = df['fruits'].str.rstrip(',').str.split(',')

# 查看结果
print(df['fruits'])

运行后即可得到符合要求的列数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 11:32:08