Pandas: adding column with the length of other column as value

Use the .str string accessor to perform string operations on DataFrames. In particular, you want .str.len:

df['name_length']  = df['seller_name'].str.len()

The resulting output:

  seller_name  name_length
0        Rick            4
1      Hannah            6

Say you have this data:

y_1980 = pd.read_csv('y_1980.csv', sep='\t')

     country  y_1980
0     afg     196
1     ago     125
2     al      23

If you want to calculate the length of any column you can use:

y_1980['length'] = y_1980['country'].apply(lambda x: len(x))
print(y_1980)

     country  y_1980  length
 0     afg     196       3
 1     ago     125       3
 2     al      23       2

This way you can calculate the length of any columns you desire.

Tags:

Python

Pandas