仅替换数字值

时间:2019-03-22 15:57:23

标签: python dataframe

如果C.values大于50,我只需将C列中的数值替换为“利润”

我有以下代码,但它取代了所有内容,而不仅仅是数字

df['C'].values[df['C'].values >= 50] = 'Profit'

我的数据框

A       B       C
test    NaN     xyz
hit     NaN     10
hit     NaN     90
hit     NaN     abc
test    val     20
test    val     90

我的输出

A       B       C
test    NaN    Profit
hit     NaN     10
hit     NaN     Profit
hit     NaN     Profit
test    val     20
test    val    Profit

我想要的输出

A       B       C
test    NaN    xyz
hit     NaN     10
hit     NaN     Profit
hit     NaN     abc
test    val     20
test    val     Profit

3 个答案:

答案 0 :(得分:3)

我在这里使用.apply(),同时使用try-except和if-else块。

类似的东西:

def convert_to_profit(value):
    try:
        if int(value) >= 50:
            return 'Profit'
        else:
            return value
    except ValueError:
        return value

df.loc[:, 'C'] = df['C'].apply(convert_to_profit)

try-except块将允许您捕获非数字值并返回未替换的值。

答案 1 :(得分:1)

更简洁的解决方案可能是:

df['C'][df['C'].apply(lambda x: x > 50 if isinstance(x, int) else False)] = 'Profit'

答案 2 :(得分:0)

您可以遍历数据框行并在需要时编辑每一行:

for idx, row in df.iterrows():
    try:
        if int(row['C']) >= 50:
            row['C'] = 'Profit'
    except ValueError:
        pass

来自熊猫文档:

  

df.iterrows()
  将DataFrame行作为(索引,系列)对进行迭代。

相关问题