gpt4 book ai didi

python - 替换列中的值

转载 作者:行者123 更新时间:2023-12-01 01:57:34 26 4
gpt4 key购买 nike

这是我的数据集,其中有四列。我想将 survival_status 列中的值(1 和 2)替换为(负数和正数)。我正在使用 pandas 来更改值。

 Age  operation_year  axillary_nodes_detected  survival_status
0 30 64 1 1
1 30 62 3 1
2 30 65 0 2
3 31 59 2 1
4 31 65 4 2

Haberman["survival_status"] = Haberman["survival_status"].apply(lambda x : 'Positive' if x == 2 else 'Negative')

应用后,它将整个列值更改为负值。

Haberman['survival_status'].value_counts()
Negative 306
Name: survival_status, dtype: int64

谁能告诉我我哪里做错了?

最佳答案

一种方法是使用字典映射。但首先请确保您的数据帧已转换为 int:

df = df.astype(int)

d = {2: 'Positive', 1: 'Negative'}

df['survival_status'] = df['survival_status'].map(d)

结果:

print(df)

Age operation_year axillary_nodes_detected survival_status
0 30 64 1 Negative
1 30 62 3 Negative
2 30 65 0 Positive
3 31 59 2 Negative
4 31 65 4 Positive

关于python - 替换列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49997683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com