Home > Backend Development > Python Tutorial > How Do I Add a New Column to an Existing Pandas DataFrame?

How Do I Add a New Column to an Existing Pandas DataFrame?

DDD
Release: 2024-12-31 00:03:17
Original
954 people have browsed it

How Do I Add a New Column to an Existing Pandas DataFrame?

Adding a Column to an Existing DataFrame

You have an indexed DataFrame with named columns and rows that are not continuous numbers. To add a new column, 'e', to the existing DataFrame without altering the data, follow these steps:

1. Determine DataFrame Length

Estimate the length of your DataFrame using the following code:

sLength = len(df1['a'])
Copy after login

2. Create a Series with the Column Values

Create a Series with randomly generated values that match the length of your DataFrame:

e_values = pd.Series(np.random.randn(sLength))
Copy after login

3. Specify the Target Column

Indicate that you want to add the new values to the 'e' column:

df1['e'] = ...
Copy after login

4. Populate the New Column

Assign the Series of values to the new 'e' column using one of the following methods:

a. Current Best Method (as of 2017)

df1 = df1.assign(e=e_values.values)
Copy after login

b. Method Prior to 2017

df1['e'] = e_values
Copy after login

By following these steps, you can successfully add a new column to your DataFrame while preserving the original data.

The above is the detailed content of How Do I Add a New Column to an Existing 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template