Applying Lambda Row on Multiple Columns Pandas
I Am Creating a Sample Dataframe: Tp = Pd. Dataframe({'Source': ['A','S','F'], 'Target': ['B','N','M'], 'Count': [0,8,4]}) and Creating a Column 'Col' Based on...
I am creating a sample dataframe:
tp = pd.DataFrame({'source':['a','s','f'],
'target':['b','n','m'],
'count':[0,8,4]})
And creating a column 'col' based on condition of 'target' column >> same as source, if matching condition, else to a default, as below:
tp['col'] = tp.apply(lambda row:row['source'] if row['target'] in ['b','n'] else 'x')
But it's throwing me this error: KeyError: ('target', 'occurred at index count')
How can I make it work, without defining a function?
1 Answer
You need to use axis=1 to tell Pandas you want to apply a function to each row. The default is axis=0.
tp['col'] = tp.apply(lambda row: row['source'] if row['target'] in ['b', 'n'] else 'x',
axis=1)
However, for this specific task, you should use vectorised operations. For example, using numpy.where:
tp['col'] = np.where(tp['target'].isin(['b', 'n']), tp['source'], 'x')
pd.Series.isin returns a Boolean series which tells numpy.where whether to select the second or third argument.