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

如何在Pandas DataFrame中依据Classification列修改Explanation列内容

解决Pandas DataFrame条件修改列内容的问题

可以通过loc方法精准定位满足条件的行,直接对目标列进行字符串拼接操作,实现需求:

步骤1:构造原始DataFrame

import pandas as pd

df = pd.DataFrame({
    'Explanation': ['blue, red, pink', 'green, red', 'yellow, purple', 'red'],
    'Classification': [1, 0, 0, 1]
})

步骤2:执行条件修改

# 给Classification为1的行的Explanation列追加", black"
df.loc[df['Classification'] == 1, 'Explanation'] += ', black'

查看结果

执行上述代码后,打印DataFrame:

print(df)

输出结果与期望一致:

Explanation  Classification
0  blue, red, pink, black               1
1           green, red               0
2        yellow, purple               0
3            red, black               1

这种方法利用Pandas的矢量化操作,比循环或apply更高效,适合处理大规模数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:48:11