Python Pandas insert records into a column according to the data present in a Dataframe

Asked

Viewed 1,219 times

0

Good evening, I have an Excel spreadsheet that has a column called Cod and within that column are the valores: 01, 02, 03

I need to create another column in this table that does the following:

  • According to the values of the column "Cod" assign the names of the Cities

Ex:

01 = São Paulo

02 = Belo Horizonte

03 = Rio de Janeiro

In other words, this other column will receive the names of Cidades in accordance with the Cod of them, I tried to do so:

data_teste = {'Cidades': ['São Paulo', 'Belo Horizonte', 'Rio de Janeiro']}
resultado = pd.DataFrame(data_teste, index=[01, 02, 03])
plan = pd.read_excel('teste.xlsx', header=3)

for i in plan['Cod'].values:
    if i in resultado.loc[i]:
        plan['Nomes Cidades] = resultado.values

But I didn’t succeed, someone could help me?

  • 1

    To show a part of the dataframe plan?

  • 1

    @Sidon good morning, my friend GBrandt managed to solve this my problem, in relation to your comment would show yes, the part that interested me was the Cod and within that column would show me several ex codes: 01, 02, 03... for each Cod inside that column would need another column called Cidades that would give the name of the correct city according to that Cod, for example the Cod 01 = São Paulo | 02 = Belo Horizonte | 03 = Rio de Janeiro basically was that, I hope you have understood this my explanation rsrs, thank you for the interest in wanting to help, vlw even!

1 answer

1


Try with pandas.Series.map:

plan['Nomes Cidades'] = plan['Cod'].map(resultado['Cidades'])
  • Thanks @Gbrandt worked perfectly the way I wanted, I knew already the map but I didn’t know it would work on this occasion, because I usually use it to go through a list, in which case he went through a Dataframe using the Key: Cidades from my dictionary, ball show know that this way works too!

Browser other questions tagged

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