如何使用loc的多个条件更改数据框中的值? [英] How to change a value in a dataframe using multiple conditions with loc?

查看:143
本文介绍了如何使用loc的多个条件更改数据框中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从数据帧的行/列中更改值,如下所示:

I want to change a value from a row/column of a dataframe as follows:

在时间间隔内,如果发现一个等于1的值,则应放置2.

Within the interval, when it found a value which is different equal to 1, then it should put 2.

示例:

初始df :

index                      event
2019-12-07 18:30:16         0
2019-12-07 19:30:16         0           
2019-12-07 20:30:16         0           
2019-12-07 21:30:16         0           
2019-12-07 22:30:16         1

需要df :

index                      event
2019-12-07 18:30:16         0
2019-12-07 19:30:16         0           
2019-12-07 20:30:16         0           
2019-12-07 21:30:16         0           
2019-12-07 22:30:16         2

以下代码有效,但我无法更改该值:

The following code works but I cannot change the value:

mask = (df.index > start_dates) & (df.index <= end_dates)

for k in range (0, len(df.loc[mask])):
    if df.loc[mask].event[k] == 1:
        df.loc[mask].loc[df.loc[mask].event == 1, "event"] = 2

我无法在代码的最后一行中将值从1更改为2.

I cannot change the value from 1 to 2 in the last line of code.

我也尝试过...

df.loc[mask].loc[df.loc[mask].event == 1, "event"] = 2
df.loc[mask].event[df.loc[mask].event == '1'] = 2
df.loc[mask].event[k] = 2

但以上所有行均无效.

请帮助我.:(非常感谢您的帮助!

Please help me. :( Any help is highly appreciated!

推荐答案

您最后尝试的三行代码是pandas称为链式定位调用",如果您要使用它们来分配新的代码,每次都会失败价值观.一个 .loc 足以满足您的需求

The three lines you tried at the end are what pandas calls "chained loc calls", which will fail every time if you want to use them to assign new values. One .loc is enough for what you want

df.loc[mask] = 2
 # or
df.loc[mask, :] = 2
# both will assign two to all columns if you have more

# or also
df.loc[mask, 'event'] = 2

不需要循环, .loc 将使用布尔掩码选择所需的行.

There is no need for the loop, .loc will select the rows you want with the boolean mask.

编辑

您可以在面罩中包括第三个条件

You can include a third condition to your mask

mask = (df.index > start_dates) & (df.index <= end_dates) & (df.event ==1)

或保留您的蒙版,并合并 .loc

Or leave your mask as it is and combine the conditions inside .loc

df.loc[mask & (df.event ==1), 'event'] = 2

这篇关于如何使用loc的多个条件更改数据框中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆