I have this dataframe df
:
JavaScript
x
10
10
1
name class
2
1 Bob history
3
2 Chuck math
4
3 Daren history
5
4 Elisa english
6
5 Aaron history
7
6 Tom math
8
7 Dan history
9
8 Fred english
10
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:
JavaScript
1
10
10
1
name class name_len class_len
2
1 Bob history 3 7
3
2 Chuck math 5 4
4
3 Daren history 5 7
5
4 Elisa art 5 3
6
5 Aaron history 5 7
7
6 Tom math 3 4
8
7 Dan history 3 7
9
8 Fred business 4 8
10
I’ve tried to use for comprehension to generate the lists at once, such as so:
JavaScript
1
2
1
df[["1", "2"]] = [df[name].apply(len) for name in posts.columns]
2
but I get
JavaScript
1
2
1
ValueError: Columns must be same length as key
2
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!
Advertisement
Answer
No need to use apply
, .str.len()
should work:
JavaScript
1
14
14
1
for col in df.columns:
2
df[f"{col}_len"] = df[col].str.len()
3
4
df
5
name class name_len class_len
6
1 Bob history 3 7
7
2 Chuck math 5 4
8
3 Daren history 5 7
9
4 Elisa english 5 7
10
5 Aaron history 5 7
11
6 Tom math 3 4
12
7 Dan history 3 7
13
8 Fred english 4 7
14