How to Replace Column Values Based on a Condition in a Pandas DataFrame?

Susan Sarandon
Release: 2024-11-01 15:38:30
Original
353 people have browsed it

How to Replace Column Values Based on a Condition in a Pandas DataFrame?

Replace Column Values Based on Condition in Pandas DataFrame

To replace specific values in a DataFrame column based on a condition, the loc indexing method should be utilized correctly. In the provided example, the task is to replace values in the 'First Season' column that exceed 1990 with the value 1.

The code provided in the question, df.loc[(df['First Season'] > 1990)] = 1, replaces all values in the entire row instead of just the 'First Season' column. To accurately target the desired column, the following syntax is required:

df.loc[df['First Season'] > 1990, 'First Season'] = 1
Copy after login

Here, the loc method selects rows where the 'First Season' column values exceed 1990. The second argument, 'First Season', specifies that only the values in that particular column should be replaced.

To generate a boolean indicator where True corresponds to values over 1990 and False otherwise, the following is recommended:

df['First Season'] = (df['First Season'] > 1990).astype(int)
Copy after login

This converts True and False values to 1 and 0, respectively.

The above is the detailed content of How to Replace Column Values Based on a Condition in a Pandas DataFrame?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!