Ask Your Question
2

How can a new column be created in a dataframe when the value meets a certain range in relation to another column's value?

asked 2023-06-07 23:51:52 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-06-08 00:00:01 +0000

djk gravatar image

To create a new column in a dataframe when a certain value meets a range in relation to another column's value, you can use pandas' "apply" method with a lambda function that checks if the value in the other column is within the desired range.

For example, if you have a dataframe called "df" with a column "A" and you want to create a new column "B" that has the string "high" if the value in column "A" is greater than 10, and "low" if it's less than or equal to 10, you can do the following:

df['B'] = df['A'].apply(lambda x: 'high' if x > 10 else 'low')

This will create a new column in the dataframe called "B" with the values 'high' or 'low' depending on the value in column "A". You can modify the lambda function to apply any range or condition you desire.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-07 23:51:52 +0000

Seen: 8 times

Last updated: Jun 08 '23