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

Create multiple columns at once based off of existing columns

I have this dataframe df:

     name  class   
1     Bob  history
2   Chuck  math     
3   Daren  history  
4   Elisa  english 
5   Aaron  history 
6     Tom  math   
7     Dan  history 
8    Fred  english

I want to create two new columns at once which are simply the character length of the existing two columns. The result should look like this:

     name     class   name_len  class_len
1     Bob   history          3          7
2   Chuck      math          5          4
3   Daren   history          5          7
4   Elisa       art          5          3
5   Aaron   history          5          7
6     Tom      math          3          4 
7     Dan   history          3          7
8    Fred  business          4          8

I’ve tried to use for comprehension to generate the lists at once, such as so:

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

df[["1", "2"]] = [df[name].apply(len) for name in posts.columns]

but I get

ValueError: Columns must be same length as key

I would like to do more complex operations and create lots of new columns from pre-existing columns as such, and do not want to manually create each new column one at a time. Any help is appreciated!

>Solution :

No need to use apply, .str.len() should work:

for col in df.columns:
    df[f"{col}_len"] = df[col].str.len()

df
    name    class  name_len  class_len
1    Bob  history         3          7
2  Chuck     math         5          4
3  Daren  history         5          7
4  Elisa  english         5          7
5  Aaron  history         5          7
6    Tom     math         3          4
7    Dan  history         3          7
8   Fred  english         4          7
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