How to create a new column 'ANO_NASCIMENTO' and insert data into it in sequence, considering each row of the column NAME

Asked

Viewed 44 times

-1

Hello!! I’m a beginner in Python and I would like to count on your help for the problems below.

I have a df with 2 columns.

NOME                      N.CELULAR           
João Pedro                98 – 9112 1632
Luís Antônio              98 – 8513 4545
Renato gome               98 – 9002 4012
Selma lira                98– 8807 1943
Luiza ving                98 – 8125 1448
Paulo junior              98 – 9056 1435
Manoel mendonça           98 – 9115 1616

I need to create a third column of name ANO_NASCIMENTO and insert/add data to it in a sequential manner, considering each row in the column NOME. I believe you’re far from what I want, but I tried the job append. The fact is I’m not sure how to do this.

df["ANO_NASC"] = ' '
ANO_NASC = [ ]
Ano_nasc = int(input('Qual o ano de seu Nascimento?'))
if Ano_nasc > 0:
    ANO_NASC.append(Ano_nasc)
else:
    print('Fim')

Any help will be welcome.

  • Are you using some library or just pure Python? If it is the second case, you can turn the second column into a list, and leave only the phones on the first! Thus, the number of each person serves to identify her.

  • I am wearing pandas

  • So I have no experience to help you. Sorry.

  • Anyway, thank you for trying.

1 answer

2


You have two options, insert directly into the column or create a list and then add the values at once. Follow the details.

Base code:

import pandas as pd

dados = [
    {"NOME": "João Pedro", "N.CELULAR": "98 – 9112 1632"},
    {"NOME": "Luís Antônio", "N.CELULAR": "98 – 8513 4545"},
    {"NOME": "Renato gome", "N.CELULAR": "98 – 9002 4012"},
    {"NOME": "Selma lira", "N.CELULAR": "98 – 8807 1943"},
    {"NOME": "Luiza ving", "N.CELULAR": "98 – 8125 1448"},
    {"NOME": "Paulo junior", "N.CELULAR": "98 – 9056 1435"},
    {"NOME": "Manoel mendonça", "N.CELULAR": "98 – 9115 1616"}
]

df = pd.DataFrame(dados)

Option 1 - Insert directly in column:

df['ANO_NASCIMENTO_Opcao_1'] = ""
for index, nome in enumerate(df['NOME']):
    texto = f'{nome}, qual o ano de seu Nascimento? '
    data = int(input(texto))
    df['ANO_NASCIMENTO_Opcao_1'].iat[index] = data

Option 2 - Insert values after obtained:

datas = list()
for nome in df['NOME']:
    texto = f'{nome}, qual o ano de seu Nascimento? '
    data = int(input(texto))
    datas.append(data)

df['ANO_NASCIMENTO_Opcao_2'] = datas

Print dataframe

print(df)

inserir a descrição da imagem aqui

  • Hello!! Your answers are good and meet the request, I managed to advance.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.