以字典D1=NameAlice Bob Jack MajorMath Art Math Age 29 30 60为基础创建一个DataFrame对象DF4将DF4中的字符串Math转换为数字0字符串Art转换为数字1;并为DF4添加新的列Age_Group该列的值为Age列的转换结果转换规则为0-29为青年30-59为中年60以上为老年输出转换后的DF4。
代码如下:
import pandas as pd
D1 = {'Name':['Alice', 'Bob', 'Jack'], 'Major':['Math', 'Art', 'Math'], 'Age': [29, 30, 60]}
DF4 = pd.DataFrame(D1)
DF4['Major'] = DF4['Major'].apply(lambda x: 0 if x == 'Math' else 1)
DF4['Age_Group'] = pd.cut(DF4['Age'], bins=[0, 29, 59, 100], labels=['青年', '中年', '老年'])
print(DF4)
输出结果为:
Name Major Age Age_Group
0 Alice 0 29 青年
1 Bob 1 30 中年
2 Jack 0 60 老年
原文地址: https://www.cveoy.top/t/topic/eP7P 著作权归作者所有。请勿转载和采集!