简体   繁体   中英

How do I change the value in a column given a Boolean (in Python)?

In a data frame, when the value of a given column is below 10, I need to change all the values till the end of the column to 5.

so let's say these are the values of the column:

A
134
413
12
81
9
483
93
30

I would need it to become:

A
134
413
12
81
5
5
5
5

I apologize if I didn't explain this well, I'm new to coding. Thanks for all the help!

You can compare the column value with 10 and get the cummax of boolean series to ensure the value after first True is True

df['out'] = df['col'].mask(df['col'].lt(10).cummax().eq(1), 5)
print(df)

   col  out
0  134  134
1  413  413
2   12   12
3   81   81
4    9    5
5  483    5
6   93    5
7   30    5

Let df = pd.DataFrame({'x': [134, 413, 12, 81, 9, 483, 93, 30, 6]}) .

  • Find the elements that are less than 10: df['x'] < 10

  • Find the row that contains the first of them: (df['x'] < 10).argmax()

  • Change that row and all the following rows to 5

     df.loc[(df['x'] < 10).argmax():, 'x'] = 5

you coutd try: myDataFrame = np.where(myDataFrame < 10, 5, myDataFrame)

this checks where the value is lower than ten. if it is it sets it to five, else it just sets the value to what it already was.

Let's assume the dataframe id df and the column name is x

col_list = df['x'].to_list()
for i in range(len(col_list)):
    if col_list[i] < 10:
        col_list[i] = 5
df['x'] = col_list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM