0

I have a dataframe in which I want to create a new column based on the values stored in another column.

foo = pd.DataFrame(
    [['USA','x',1,2],
    ['Canada','y',2,4],
    ['Australia','x',3,6]], 
    columns = ('Country', 'C1','x', 'y')
)

For example, given following dataframe

    Country     C1  x   y
0   USA         x   1   2
1   Canada      y   2   4
2   Australia   x   3   6

I want to create a new column say z but the column C1 decides where the value of z will be coming from column x or column y. In other words, I want to do something like

foo['z']=foo[foo['C1']]

The column C1 can have one of 28 different values. The question is different from the question referred in the comments as I do not want to calculate values on the basis of pre existing values rather the value in one of the column ( C1 in this case) contains the name of the column whose value should be stored in the new column.

Wai Ha Lee
  • 8,173
  • 68
  • 59
  • 86
MARK
  • 2,202
  • 4
  • 24
  • 43
  • Possible duplicate of [Pandas: create two new columns in a dataframe with values calculated from a pre-existing column](http://stackoverflow.com/questions/12356501/pandas-create-two-new-columns-in-a-dataframe-with-values-calculated-from-a-pre) – klib Nov 01 '15 at 22:52
  • You said: "column C1 decides where the value of z will be coming from column x or column y." How will `C1` decide exactly? Based on what condition? – Joe T. Boka Nov 01 '15 at 23:01
  • C1 will have the name of the column whose value should be used as the value of z for this particular row – MARK Nov 01 '15 at 23:02
  • `C1` will have 28 different values so there will be 30 columns in the `df` including `C1` and `z`? What am I missing? – Joe T. Boka Nov 01 '15 at 23:11
  • The value for z can come from any of other 28 columns. In other words C1 is storing column names. if C1 's value is x then foo['z'] will be equal to foo['x'] – MARK Nov 01 '15 at 23:15

1 Answers1

2
foo['z']=foo.apply(lambda x: x[x['C1']], axis=1)
Charlie Haley
  • 3,612
  • 4
  • 21
  • 36