Home > Backend Development > Python Tutorial > How to Efficiently Add a New Column to a Pandas DataFrame?

How to Efficiently Add a New Column to a Pandas DataFrame?

Mary-Kate Olsen
Release: 2024-12-14 03:23:10
Original
529 people have browsed it

How to Efficiently Add a New Column to a Pandas DataFrame?

How to Add a New Column to an Existing DataFrame

Problem Statement

Given a DataFrame with indexed rows, you want to incorporate an additional column without modifying the existing data. For instance, given the DataFrame:

</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">      a         b         c         d
Copy after login

2 0.671399 0.101208 -0.181532 0.241273
3 0.446172 -0.243316 0.051767 1.577318
5 0.614758 0.075793 -0.451460 -0.012493

Add a column named 'e' with the following values:

<br>0   -0.335485<br>1   -1.166658<br>2   -0.385571<br>dtype: float64<br>

Solution

Edit 2017

The most efficient method, as suggested by @Alexander and indicated in the comments, is to use the assign method:

df1 = df1.assign(e=pd.Series(np.random.randn(sLength)).values)
Copy after login

Edit 2015

Some users reported encountering the SettingWithCopyWarning with the original code. However, the code remains functional in the current pandas version, 0.16.1.

sLength = len(df1['a'])

df1['e'] = pd.Series(np.random.randn(sLength), index=df1.index)
Copy after login

Original Answer

Create a Series using the original indexes of df1 and assign it to the new column:

df1['e'] = pd.Series(np.random.randn(sLength), index=df1.index)
Copy after login

The above is the detailed content of How to Efficiently Add a New Column to a Pandas DataFrame?. 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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template