简体   繁体   中英

Python beginner

I have an existing dataset imported as excel file. Within the imported file I want to

  1. Create a new column then
  2. Assign parameters from an existing column. Example. If in column x the age is >17 and <23 assign generation z under colum y else if in colum x the age is >24 but less than <40 assign to mill in column y

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM