3

我有两个这样的熊猫数据框:

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

我想要的输出:df3

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

我怎样才能有效地实现这一目标?

4

2 回答 2

4

使用第一rename列以获得更好的性能,然后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

最后添加df1喜欢:

df = df1.merge(df2, on='pricing_type', how='left')
于 2021-02-16T12:32:03.857 回答
0

我会使用转置方法。对于这个问题,您似乎并不需要担心加入特定字段,而只需将一列df2df1

#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)

如果你想移动多行,你只需改变

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

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

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

并选择您需要的列

于 2021-02-16T12:49:44.020 回答