Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

248
Visualizações
Pandas: adding column with the length of other column as value

I want to add an additional column to an existing dataframe that has the length of the 'seller_name' column as its value.

The output should be like so:

seller_name    name_length
-------------|-------------
Rick         |      4
Hannah       |      6

However, I'm having difficulty getting the code right.

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

just gives me the length of the entire column (6845) And

df['nl']  = df[len('seller_name')]

Throws a KeyError.

Does anyone know the correct command to achieve my goal?

Many thanks!

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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
over 4 years ago · Santiago Trujillo Relatório

0

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda