python - 使用 Pandas 将特定值添加到根据条件选择的行

标签 python pandas

如果我有以下数据框:

id        fruits
01     Apple, Apricot
02     Apple, Banana, Clementine, Pear
03     Orange, Pineapple, Pear

我想将 Fruit 添加到 Apple 所在的行以生成如下所示的新数据框:

id        fruits
01     Apple, Apricot, Fruit
02     Apple, Banana, Clementine, Pear, Fruit
03     Orange, Pineapple, Pear

我该怎么做?谢谢。抱歉,我编造这个例子来代表我真正的问题。

最佳答案

第一个有效的黑客

fruit = np.array(', Fruit', object)
df.fruits + df.fruits.str.contains('Apple') * fruit

0                     Apple, Apricot, Fruit
1    Apple, Banana, Clementine, Pear, Fruit
2                   Orange, Pineapple, Pear
Name: fruits, dtype: object
<小时/>

更合理

df.loc[df.fruits.str.contains('Apple'), 'fruits'] += ', Fruit'
df

   id                                  fruits
0   1                   Apple, Apricot, Fruit
1   2  Apple, Banana, Clementine, Pear, Fruit
2   3                 Orange, Pineapple, Pear

__

为了解决评论问题,当 fruits 列中的元素不是字符串时,会出现 NA。这意味着数据很差。没关系,我们可以填写 NA

谢谢jezrael改进实现。

df.loc[df.fruits.str.contains('Apple', na=False), 'fruits'] += ', Fruit'
df

关于python - 使用 Pandas 将特定值添加到根据条件选择的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51094020/

相关文章:

python - 安装 pip Python

python - Pandas 加入/合并/合并两个数据帧

python - 计算列表中元素出现次数的 pythonic 方法是什么?

python - 使用 Pandas 转换时间序列数组中包含周期的数据帧

python - 当存在重复项时如何合并两个计数向量化器?

python - 使用 numpy 进行下采样

python - 这 3 个 pytest 装置的功能差异是什么?

python - 如何在 pandas 中删除重复项但保留比第一个更多的项

Python:尝试交叉应用两个数据框

Python/Pandas 仅将字符串转换为时间