I have an existing dataset imported as excel file. Within the imported file I want to
Code was
If df[‘age’]>17 and df[‘age’]<23:
Df[‘generation’]=“genZ”
Élif df[‘age’]>24 and df[‘age’]<40
Df[‘generation’]=“Millenial”
You should use pd.cut()
for this.
data = [18, 19, 17, 27, 25, 24, 39]
columns = ['age']
df = pd.DataFrame(data=data, columns=columns)
df['generation'] = pd.cut(df['age'], [17, 24, 40], labels=['Genz', 'Millenial'])
Output
age generation
0 18 Genz
1 19 Genz
2 17 NaN
3 27 Millenial
4 25 Millenial
5 24 Genz
6 39 Millenial
I would create a custom function and use map()
.
def generation(age):
if (age > 17) & (age < 24):
return "GenZ"
elif (age > 24) & (age < 40):
return "Millenial"
else:
return "Not classified"
Then we pass it to our dataframe:
df['generation'] = df['Age'].map(lambda x: generation(x))
An option via np.select :
import numpy as np
import pandas as pd
df = pd.DataFrame([17, 18, 19, 23, 24, 25, 39, 40, 41], columns=['age'])
df['generation'] = np.select(
[(df['age'] > 17) & (df['age'] < 23),
(df['age'] > 24) & (df['age'] < 40)],
['genZ', 'Millenial'],
default=None)
print(df)
df
:
age generation
0 17 None
1 18 genZ
2 19 genZ
3 23 None
4 24 None
5 25 Millenial
6 39 Millenial
7 40 None
8 41 None
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.