更新熊猫数据框单元格值

时间:2019-12-20 19:36:37

标签: python pandas pandas-groupby

如果pandas df单元格包含负整数,则将其更新为“负”,如果包含正整数,则将其更新为“正”

初始df

ID        Score
apple    -10.5
mango     5.36
banaba   -89.6
carrot    5.3

预期结果

ID       Score
apple    Negative
mango    Positive
banaba   Negative
carrot   Positive

我尝试如下进行“负面”更新:

df_up = df[df['Score'] < 0] = 'Negative'

但出现错误

4 个答案:

答案 0 :(得分:1)

您必须将Score列转换为数字类型,然后进行如下转换:

>>> df.Score = df.Score.astype(int)
>>> df
       ID  Score
0   apple    -10
1   mango      5
2  banaba    -89
3  carrot      5

>>> df.Score = np.where(df.Score < 0, "Negative", "Positive")
>>> df
       ID     Score
0   apple  Negative
1   mango  Positive
2  banaba  Negative
3  carrot  Positive

答案 1 :(得分:1)

如果您Score是文本,则可以执行以下操作:

 df['Score'] = np.where(df['Score'].str.startswith('-'), 'Negative', 'Positive')

输出:

       ID     Score
0   apple  Negative
1   mango  Positive
2  banaba  Negative
3  carrot  Positive

答案 2 :(得分:0)

您可以使用np.where

import pandas as pd
import numpy as np

df = pd.DataFrame(data={'ID': ['apple', 'mango', 'banaba', 'carrot'],
                        'Score': [-10.5, 5.36, -89.6, 5.3]})

df['Score'] = np.where(df['Score'] < 0, 'Negative', 'Positive')

df
       ID     Score
0   apple  Negative
1   mango  Positive
2  banaba  Negative
3  carrot  Positive

答案 3 :(得分:0)

这也会设置它们:

df['Score']= df['Score'].apply(lambda x: 'Positive' if x > 0 else 'Negative') 

       ID     Score
0   apple  Negative
1   mango  Positive
2  banaba  Negative
3  carrot  Positive