编写Python程序将'qualify'列的'yes'/'no'替换为True/False
How to Replace 'yes'/'no' with True/False in the 'qualify' Column Using Python
Got it, let's break down how to solve this problem—whether you're working with a pandas DataFrame (the most common scenario for tabular data) or a basic list, I've got you covered.
Using Pandas (Recommended for Tabular Data)
If your data is stored in a pandas DataFrame, the replace() method is super straightforward. Here's a complete example:
import pandas as pd # Sample DataFrame (replace this with your actual data source, like pd.read_csv()) data = { 'name': ['Alice', 'Bob', 'Charlie', 'Diana'], 'qualify': ['yes', 'no', 'yes', 'no'] } df = pd.DataFrame(data) # Replace 'yes' with True and 'no' with False in the 'qualify' column df['qualify'] = df['qualify'].replace({'yes': True, 'no': False}) # Print the processed result print(df)
Output:
name qualify 0 Alice True 1 Bob False 2 Charlie True 3 Diana False
Alternatively, you can use map() for the same result—this is handy if you want to reuse the mapping elsewhere:
qualify_mapping = {'yes': True, 'no': False} df['qualify'] = df['qualify'].map(qualify_mapping)
For a Basic List
If your 'qualify' data is just a regular Python list, you can use a list comprehension for a quick fix:
qualify_list = ['yes', 'no', 'yes', 'yes', 'no'] processed_list = [True if item == 'yes' else False for item in qualify_list] print(processed_list) # Output: [True, False, True, True, False]
Both methods are efficient and easy to read—pick whichever fits your data structure best!
内容的提问来源于stack exchange,提问作者Anandh Kirupa
相关产品推荐
相关产品推荐

