Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading