Although the answers given are correct, they change the initial data frame, which is not always desirable (and given that the OP asked for examples βusing apply β, they probably need a version that returns a new data frame, as apply does).
This is possible using the assign command: this is valid for assign existing columns, as the documentation reads (highlighted mine):
Assign new columns to the DataFrame.
Returns a new object with all source columns in addition to new ones. Existing columns to be reassigned will be overwritten .
In short:
In [1]: import pandas as pd In [2]: df = pd.DataFrame([{'a': 15, 'b': 15, 'c': 5}, {'a': 20, 'b': 10, 'c': 7}, {'a': 25, 'b': 30, 'c': 9}]) In [3]: df.assign(a=lambda df: df.a / 2) Out[3]: abc 0 7.5 15 5 1 10.0 10 7 2 12.5 30 9 In [4]: df Out[4]: abc 0 15 15 5 1 20 10 7 2 25 30 9
Thibaut Dubernet Jun 26 '19 at 8:02 am 2019-06-26 08:02
source share