TFC
TFC

Reputation: 546

Add a column to the data frame doing element wise operation

Basically, pandas can copy the column by

df['B'] = df['A'] + 1

Now, I have a column of strings and I want to add a column whose values are the lengths of each string. For example,

A.      B
"hello" 5
"hi"    2

Is it possible to add B without looping?

Upvotes: 1

Views: 417

Answers (3)

ahnirab
ahnirab

Reputation: 168

You can use apply to get the length of column

df['B'] = df['A'].apply(len)

A.      B
"hello" 5
"hi"    2

Upvotes: 0

David Erickson
David Erickson

Reputation: 16683

You can use map(len):

df['B'] = df['A'].map(len)

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150745

Use str.len:

df['B'] = df['A'].str.len()

Upvotes: 3

Related Questions