Home > Backend Development > Python Tutorial > How to Create Multiple New Columns from a Single Function Output in Pandas?

How to Create Multiple New Columns from a Single Function Output in Pandas?

Mary-Kate Olsen
Release: 2024-10-28 15:09:02
Original
398 people have browsed it

How to Create Multiple New Columns from a Single Function Output in Pandas?

Creating Multiple New Columns with Pandas Function

In Pandas, it's possible to apply a single function to a column and create multiple new columns based on the output values.

Consider the following scenario:

You have a function, extract_text_features, that accepts a text column and returns 6 output columns. While the function itself works, assigning the output to specific columns poses a challenge.

Solution using Zip:

One effective approach is to use the zip function to assign the output values to multiple columns:

<code class="python">def powers(x):
    return x, x**2, x**3, x**4, x**5, x**6

df = pd.DataFrame([[i] for i in range(10)], columns=['num'])
df['p1'], df['p2'], df['p3'], df['p4'], df['p5'], df['p6'] = zip(*df['num'].map(powers))</code>
Copy after login

Here, the map() function applies powers to each row of the 'num' column, and zip unpacks the output into individual columns.

This method efficiently generates multiple new columns based on the output values of the function. It's also compatible with older versions of Pandas, unlike some other solutions that rely on newer features like df.assign().

The above is the detailed content of How to Create Multiple New Columns from a Single Function Output in Pandas?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template