Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

python - How to change a value in a dataframe using multiple conditions with loc?

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

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

The example:

initial 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

wanted 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

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

I also tried this...:

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

But none of the above lines works.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

Edit

You can include a third condition to your mask

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...