如何在pandas中替换列中的值?

2024-09-29 03:40:44 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我第一次使用Python和熊猫(请帮助这个老人)。我有一个带有浮点数和负数的列,我想用条件替换它们。 也就是说,如果数字在-2和-1.6之间,则全部替换为-2等。 如何创建条件(使用if else或other)来修改我的列。多谢了

mean=[]

for row in df.values["mean"]:
    if row <= -1.5:
        mean.append(-2)
    elif row <= -0.5 and =-1.4:
        mean.append(-1)
    elif row <= 0.5 and =-0.4:
        mean.append(0)
    else:
       mean.append(1)
df = df.assign(mean=mean)

不起作用

The column


Tags: anddfforif数字mean条件else
1条回答
网友
1楼 · 发布于 2024-09-29 03:40:44

创建一个定义条件的函数,然后将其应用于列(我根据自己的想法修复了一些条件):

df = pd.read_table('fun.txt')
# create function to apply for value ranges
def labels(x):
    if x <= -1.5:
        return(-2)
    elif -1.5 < x <= -0.5:
        return(-1)
    elif -0.5 < x < 0.5:
        return(0)
    else:
        return(1)

df['mean'] = df['mean'].apply(lambda x: labels(x)) # apply your function to your table
print(df)

应用返回相同结果的函数的另一种方法:

df['mean'] = df['mean'].map(labels)

你知道吗乐趣.txt地址:

mean
0
-1.5
-1
-0.5
0.1
1.1

从上面输出:

   mean
0     0
1    -2
2    -1
3    -1
4     0
5     1

相关问题 更多 >