如果我有以下数据框:
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/