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