在 Pandas 中将包含 'yes' 和 'no' 值的列替换为 True 和 False | Python2024 年 8 月 29 日 | 阅读 6 分钟 数据框中的值会逐渐被不同的值替换。这与使用 .loc 或 .iloc 进行更新不同,它们需要您指定要用某个值更新的位置。 to_replace: str, regex, list, dict, Series, int, float, or None 将被替换的值的查找方式。 numeric, str or regex
List of str, regex, or numeric
dict
无
值
inplace: Boolean, default False
limit: int, default None
regex: bool or same types as to_replace, default False
method: {'pad', 'ffill', 'bfill', None}
Returns:
Raises:
Value Error
示例数据框Std data = {'name of the student': ['Ajay', 'Sai', 'Chikky', 'Pavani', 'Pojitha', 'Michael', 'Sri', 'Devi', 'David', 'Gopal'], 'Scores of the Student': [11.5, 7, 20.5, np.nan, 6, 21, 22.5, np.nan, 10, 30], 'Number of attempts': [10, 9, 5, 6, 7, 2, 8, 3, 2, 1], 'Pass': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']} labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 每个列的值将是 name: 'Anil', score: 18.5, Number of attempts: 1, Pass: 'yes', label: 'k' 示例 输出 The Original rows of the student data is: Number of attempts name of the student Pass Scores a 10 Ajay yes 11.5 b 9 Sai no 7.0 c 5 Chikky yes 20.5 d 6 Pavani no NaN e 7 Pojitha no 6.0 f 2 Michael yes 21.0 g 8 Sri yes 22.5 h 3 Devi no NaN i 2 David no 10.0 j 1 Gopal yes 30.0 Here, we are replacing the 'Pass' column contains the values 'yes' and 'no' with True and False: Number of attempts name of the student Pass Scores a 10 Ajay True 11.5 b 9 Sai False 7.0 c 5 Chikky True 20.5 d 6 Pavani False NaN e 7 Pojitha False 6.0 f 2 Michael True 21.0 g 8 Sri True 22.5 h 3 Devi False NaN i 2 David False 10.0 j 1 Gopal True 30.0 使用 DataFrame.replace() 方法此方法用于从数据框中替换字符串、正则表达式、列表、字典、系列、数字等。 语法 示例 输出 The Original rows of the student data is: Number of attempts name of the student Pass Scores a 10 Ajay yes 11.5 b 9 Sai no 7.0 c 5 Chikky yes 20.5 d 6 Pavani no NaN e 7 Pojitha no 6.0 f 2 Michael yes 21.0 g 8 Sri yes 22.5 h 3 Devi no NaN i 2 David no 10.0 j 1 Gopal yes 30.0 Here, we are replacing the 'Pass' column contains the values 'yes' and 'no' with True and False: Number of attempts name of the student Pass Scores a 10 Ajay True 11.5 b 9 Sai False 7.0 c 5 Chikky True 20.5 d 6 Pavani False NaN e 7 Pojitha False 6.0 f 2 Michael True 21.0 g 8 Sri True 22.5 h 3 Devi False NaN i 2 David False 10.0 j 1 Gopal True 30.0 |
我们请求您订阅我们的新闻通讯以获取最新更新。