Home > other >  Create multiple columns at once based off of existing columns
Create multiple columns at once based off of existing columns

Time:10-03

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:

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!

CodePudding user response:

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
  • Related