Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

6
  • 17
    Note that, with much larger dataframes (think pd.DataFrame({'Type':list('ABBC')*100000, 'Set':list('ZZXY')*100000})-size), numpy.where outpaces map, but the list comprehension is king (about 50% faster than numpy.where). Commented Apr 20, 2017 at 16:45
  • 5
    Can the list comprehension method be used if the condition needs information from multiple columns? I am looking for something like this (this does not work): df['color'] = ['red' if (x['Set'] == 'Z') & (x['Type'] == 'B') else 'green' for x in df]
    – Matti
    Commented Jan 1, 2019 at 6:42
  • 2
    Add iterrows to the dataframe, then you can access multiple columns via row: ['red' if (row['Set'] == 'Z') & (row['Type'] == 'B') else 'green' for index, row in in df.iterrows()] Commented Jan 14, 2019 at 1:38
  • 1
    Note this nice solution will not work if you need to take replacement values from another series in the data frame, such as df['color_type'] = np.where(df['Set']=='Z', 'green', df['Type']) Commented Sep 17, 2019 at 15:28
  • 4
    @cheekybastard Or don't, since .iterrows() is notoriously sluggish and the DataFrame shouldn't be modified while iterating.
    – AMC
    Commented Feb 10, 2020 at 1:51