#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    5
    Rep Power
    0

    Help with simple loop


    Working in Pandas I have this dataframe df
    Code:
    df = DataFrame({'A': ['Joe', 'Joe', 'Joe', 'Joe'], 'B': ['John', 'Doug', 'Bob', 'Steve'], 'C': [True, False, False, True], 'D': ['X', 'X', 'X', 'X']})
    All I want to do is have column D take the value of column A when C is True and when C is False to take the value of column B.

    When I try
    Code:
    for i in df: 
        if df.C == True: 
            df.D = frame2.A 
        else: 
             df.D = frame2.B
    i get this error message
    ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
    So I try
    Code:
    for i in df: 
        if df.C.any(): 
            df.D = df.A 
        else: 
            df.D = df.B
    but that puts all Joe in Column D which isn't what I want.
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,892
    Rep Power
    481
    I think this is the numpy where function.

    Code:
    >>> d={'A': ['Joe', 'Joe', 'Joe', 'Joe'],
    ... 'B': ['John', 'Doug', 'Bob', 'Steve'],
    ... 'C': [True, False, False, True],
    ... 'D': ['X', 'X', 'X', 'X']}
    >>> def where(b,t,f): # boolean, values_for_true, values_for_false
    ...     return [(F,T,)[B] for (B,T,F,) in zip(b,t,f,)]
    ... 
    
    >>> where(d['C'],d['A'],d['B'])
    ['Joe', 'Doug', 'Bob', 'Joe']
    >>>
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    5
    Rep Power
    0
    Yea, that works. Thanks

    Could you explain the function you made a little more?
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,892
    Rep Power
    481
    I encourage you to read python documents and try experiments at the python prompt.
    zip, tuple assignment, tuple syntax, list comprehension, indexing, and numeric value of True and False. zip and tuple assignment work differently between python 2 and 3.
    For instance, to test zip use something like

    >>> list(zip('abc00000','def111111','ghi22222222'))
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo