Home >Backend Development >Python Tutorial >How to Efficiently Create Multiple New Columns from a Single Text Column in Pandas?

How to Efficiently Create Multiple New Columns from a Single Text Column in Pandas?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-29 08:27:03598browse

How to Efficiently Create Multiple New Columns from a Single Text Column in Pandas?

Using Pandas to Create Multiple New Columns Based on a Single Text Column

Problem:

Extracting multiple values from a text column in Pandas and assigning them correctly to new columns proves a challenge.

Solution:

To efficiently apply a function that returns multiple values to a Pandas column, utilize the zip() function. This solution improves performance significantly compared to iterating with df.iterrows().

Implementation:

<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>

Example Output:

num p1 p2 p3 p4 p5 p6
0 0 0 0 0 0 0
1 1 1 1 1 1 1
2 2 4 8 16 32 64
3 3 9 27 81 243 729
4 4 16 64 256 1024 4096
5 5 25 125 625 3125 15625
6 6 36 216 1296 7776 46656
7 7 49 343 2401 16807 117649
8 8 64 512 4096 32768 262144
9 9 81 729 6561 59049 531441

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

Statement:
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