0

I am new to the forum and python. I have been looking all over and may have come across my answer, but can't seem to figure out how to perform a seemingly simple task. Any guidance/hand holding would be really appreciated.

I would like to create a Series in a DataFrame based on conditions from several other columns. From what I can gather, this can be done by creating a function and applying to the Series/DataFrame.

def g(x):
    if notnull(f['a']):
        f['a']

    elif notnull(f['b']):
        f['b']

f['c'] = f.apply(x)
Kartik
  • 8,347
  • 39
  • 73
  • Google and find the `.fillna()` method of pandas dataframe. – Kartik Aug 10 '16 at 02:15
  • @Kartik, thanks for this--i hadn't thought of doing that. but if i have several columns (n columns) that i want to compare, it seems like i would have to create n-1 columns to get a complete series. i did a union on a few dataframes. the idea is that there will only be 1 non null value in each row. is there a quicker way of doing this? thanks so much. – sillypanda Aug 10 '16 at 02:32
  • What exactly do you want to do? It appears from the code in your answer that you want to return whatever value is not missing from a column, and if missing, return from the next column down. In any case, if you have n candidates, you will have to write n-1 conditions, and hope that you'll get a result much before checking all of them. – Kartik Aug 10 '16 at 02:35
  • I think you want this: http://stackoverflow.com/questions/11869910/pandas-filter-rows-of-dataframe-with-operator-chaining – Merlin Aug 10 '16 at 02:56
  • or tihis http://stackoverflow.com/questions/21415661/logic-operator-for-boolean-indexing-in-pandas – Merlin Aug 10 '16 at 02:57
  • Also, take a minute to read the first post in this: https://github.com/pydata/pandas/issues/13111 `.apply` is essentially a loop, and should be avoided/used when all other alternatives are exhausted, as Jeff explains in the post. – Kartik Aug 10 '16 at 03:24
  • thanks for all of the feedback and resources--super helpful. – sillypanda Aug 10 '16 at 03:54

0 Answers0