3

I have two pandas dataframes like this:

df1:

Product  pricing_type
prod1    I
prod2    p
prod3    E

df2:

id  internal_price  external price pilot_price
1    0.7             0.89             0.3

The output I want: df3

Product  pricing_type  price
prod1    I              0.7
prod2    P              0.3
prod3    E              0.89

How can I achieve this efficiently?

1
  • Is multiple rows in df2 ? Do you need match values by pricing_type ?
    – jezrael
    Feb 16, 2021 at 12:40

2 Answers 2

4

Use for better performance first rename columns and then DataFrame.melt:

d = {'internal_price':'I','external price':'E','pilot_price':'p'}
df2 = df2.rename(columns=d).melt('id', var_name='pricing_type', value_name='price')
print (df2)
   id pricing_type  price
0   1            I   0.70
1   1            E   0.89
2   1            p   0.30

And last add to df1 like:

df = df1.merge(df2, on='pricing_type', how='left')
9
  • why melt and not transpose? what's the difference?
    – Qdr
    Feb 16, 2021 at 12:38
  • 1
    @Qdr - because I think in df2 is multiple rows.
    – jezrael
    Feb 16, 2021 at 12:40
  • Even thought df2 is multiple rows, Transpose would just turn those rows into columns. Then from there you can loop through the columns to get the one you want Feb 16, 2021 at 12:56
  • @swagless_monk - Why use loops if need always avoid it if need performance?
    – jezrael
    Feb 16, 2021 at 12:57
  • If I understand that correctly, a single loop will not drastically impact performance. Feb 16, 2021 at 12:59
0

I would make use of the transpose method. For this problem, it seems like you don't really need to worry about joining on a particular field, but just to move one column from df2 to df1

#transpose the dataframe with the row values
df2 = df2.T.reset_index()

#column you want to join (since the 'id' value from df2 is 1)
prices = df2[1]

#add column to dataframe
df1 = df1.join(prices)

If you wanted to move multiple rows, you would just change

#column you want to join
prices = df2[1]

#add column to dataframe
df1 = df1.join(prices)

to

for col in df2:
    df1 = df1.join(df2[col])

and select the columns you need

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.