Add a new column in a Dataframe after comparing data with another Dataframe?

Asked

Viewed 122 times

0

I have a dataframe df_currency and need to insert new column based on comparison with another dataframe df_quotation.

Below I have dataframe only with the names of coins:

df_moeda=pd.DataFrame({"Moeda":["BTC", "ETH","WAVES","ADA"]})

Dataframe df_currency:

   Moeda
0    BTC
1    ETH
2  WAVES
3    ADA

Below the dataframe with the quotation of the pairs currency:

df_cotacao=pd.DataFrame({"Pares":["ETH-BRL", "ADA-BRL","BTC-BRL","WAVES-BRL"], "Cotação":["12", "34", "56", "78"]})

Dataframe df_quotation:

       Pares Cotação
0    ETH-BRL      12
1    ADA-BRL      34
2    BTC-BRL      56
3  WAVES-BRL      78

As a result, I want to add a column in the dataframe df_currency inserting the corresponding currency count.

  • Note: Both dataframes do not have the same coin sequence.

The dataframe df_currency should look like this:

   Moeda     Cotação
0    BTC          56
1    ETH          12
2  WAVES          78
3    ADA          34

1 answer

1


What you want to do (at least it is what it looks like) does not need to join two data frames, because the data frame quotation itself already brings the information you want.

df_cotacao['Moeda'] = df_cotacao['Pares'].apply(lambda x: x[:-4])
df_novo = df_cotacao.drop(columns= 'Pares')
df_novo[['Moeda','Cotação']]
  1. Slicing to get the names
  2. Removes the column
  3. Sorts the display of columns (variables)

Exit:

    Moeda   Cotação
    ETH     12
    ADA     34
    BTC     56
    WAVES   78
  • 2

    Very good solution. I would use .apply(lambda x: x.split("-")[0]) instead of .apply(lambda x: x[:-4]). But for the example offered in the question both work.

  • Paulo speaks, good afternoon! This option you proposed is also very good. Yesterday in a question from the same author I suggested these two approaches! Big hug!!

  • 1

    Thanks for the solution, but if df_currency had a balance column of each currency, how would the solution be? I think it would be better to add a new column of df_currency. I did not elaborate very well the question.

  • 1

    I was able to reply to my previous comment with the question indicated by @lmonferrari Thanks people!!

Browser other questions tagged

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