Python 在遍历数据帧列时,如何使用if-else条件来合并值并创建新列?
Python 在遍历数据帧列时,如何使用if-else条件来合并值并创建新列?,python,pandas,Python,Pandas,dataset['Age'].value\u counts() 这里dataset['Age']是数据帧数据集的一列。我正在尝试在中创建一个新列 名为dataset['Age in Num']的同一数据帧,其中所有原始值将分组到 #just 4 categories 18-23-NEW VOTER as 18 24-35-YOUNG VOTER as 24 36-55-MATURED VOTER as 36 the remaining values as 56 我使用了以
dataset['Age'].value\u counts()
这里dataset['Age']
是数据帧数据集的一列。我正在尝试在中创建一个新列
名为dataset['Age in Num']
的同一数据帧,其中所有原始值将分组到
#just 4 categories
18-23-NEW VOTER as 18
24-35-YOUNG VOTER as 24
36-55-MATURED VOTER as 36
the remaining values as 56
我使用了以下代码,但它不起作用
for Age in dataset['Age']:
if Age == '24-35-YOUNG VOTER':
dataset['Age in Num'] = 24
elif Age == '36-55-MATURED VOTER':
dataset['Age in Num'] = 36
elif Age == '18-23-NEW VOTER':
dataset['Age in Num'] = 18
else:
dataset['Age in Num'] = 56
#then when i typed dataset['Age in Num']
#i got this
0 36
1 36
2 36
3 36
4 36
5 36
6 36
7 36
8 36
9 36
10 36
11 36
12 36
13 36
14 36
所有值仅为36。。。。感谢您的帮助这正是您需要的:
def test(Age):
if Age == '24-35-YOUNG VOTER':
return 24
elif Age == '36-55-MATURED VOTER':
return 36
elif Age == '18-23-NEW VOTER':
return 18
else:
return 56
df['Age in Num']=df.Age.apply(lambda x: test(x))
输出(示例):
如果我们看不懂你的代码,我们就帮不了你。看见
def test(Age):
if Age == '24-35-YOUNG VOTER':
return 24
elif Age == '36-55-MATURED VOTER':
return 36
elif Age == '18-23-NEW VOTER':
return 18
else:
return 56
df['Age in Num']=df.Age.apply(lambda x: test(x))
Age Age in Num
0 1 56
1 32 56
2 24-35-YOUNG VOTER 24
3 24-35-YOUNG VOTER 24
4 36-55-MATURED VOTER 36
5 18-23-NEW VOTER 18