0

I'm working on a script to do some pricing. Have a dataframe which contains a quantity list:

Name Volume Area
Wood 133 256
Steel 55 330

(and 1800 more lines like those)

What I need to do is create a third column in the df that contains the "true" quantity. Pretty much, on some materials it's the volume, on others it's the area.

Name Volume Area Qty
Wood 133 256 133
Steel 55 330 330

So far I've thought to create a dictionary:

my_dict = {'Wood':'Volume', 'Steel':'Area'}

Using map (or replace) I put that into a column in the df:

Name Volume Area Datafield
Wood 133 256 Volume
Steel 55 330 Area

Now, how would I go about putting the quantity into the Quantity column, based on what Datafield says?

I tried

df['Quantity'] = df[df['Datafield']]

But, it crashed and I'm stuck.

Stgauss
  • 57
  • 1
  • 5

1 Answers1

1

TRY:

df['QTY'] = df.lookup(df.index, df['Datafield'])

Alternative:

df['QTY'] = df.apply(lambda x: x[x['Datafield']],1)

Another alternative via melt:

k = df.melt('Datafield')
df['QTY'] = k[k.Datafield.eq(k.variable)]['value'].values
OUTPUT:
   Name  Volume  Area Datafield  QTY
0   Wood     133   256    Volume  133
1  Steel      55   330      Area  330
Nk03
  • 14,699
  • 2
  • 8
  • 22