Home > other >  Python/Pandas: apply my own rule to a column and put it in a specific position
Python/Pandas: apply my own rule to a column and put it in a specific position

Time:04-10

I have a table with 10 columns. Let's say that the column_1 is a name and if the name ends in letter 'a' I want to create a rule which would fill my new column to 'Female'. In other cases it would be 'Male'. I want this new column to be right after column1 so I get something like:

df1:

  1. Adam Male (other coulmns)
  2. Elena Female (other coulmns)
  3. Jack Male (other coulmns)
  4. Jessica Female (other coulmns)

CodePudding user response:

You can use insert:

df.insert(1, 'Name', np.where(df['col1'].str.endswith('a'), 'Female', 'Male'))

Or, if you don't know the position of 'col1':

pos = df.columns.get_loc('col1') 1
df.insert(pos, 'Name', np.where(df['col1'].str.endswith('a'), 'Female', 'Male'))

output:

      col1    Name  col2
0     Adam    Male     0
1    Elena  Female     1
2     Jack    Male     2
3  Jessica  Female     3

used input:

df = pd.DataFrame({'col1': ['Adam', 'Elena', 'Jack', 'Jessica'], 'col2': range(4)})
  • Related