Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pandas.DataFrame.assign: how to refer to newly created columns?

I’m trying to use pandas.DataFrame.assign in Pandas 1.5.2. Let’s consider this code, for instance:

df = pd.DataFrame({"col1":[1,2,3], "col2": [4,5,6]})
df.assign(
    test1="hello",
    test2=df.test1 + " world"
)

I’m facing this error:

AttributeError: ‘DataFrame’ object has no attribute ‘test1’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, it’s explicitly stated in the documentation that:

Assigning multiple columns within the same assign is possible. Later items in **kwargs may refer to newly created or modified columns in df; items are computed and assigned into df in order.

So I don’t understand: how can I refer to newly created or modified columns in df when calling assign?

>Solution :

You can pass a callable to assign. Here use a lambda to reference the DataFrame.

Parameters
**kwargsdict of {str: callable or Series}

The column names are keywords. If the values are callable, they are computed on the DataFrame and
assigned to the new columns.
The callable must not change input
DataFrame (though pandas doesn’t check it). If the values are not
callable, (e.g. a Series, scalar, or array), they are simply assigned.

df = pd.DataFrame({"col1":[1,2,3], "col2": [4,5,6]})

df.assign(
    test1="hello",
    test2=lambda d: d.test1 + " world"
)

Output:

   col1  col2  test1        test2
0     1     4  hello  hello world
1     2     5  hello  hello world
2     3     6  hello  hello world
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading