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
DDDOriginal
2024-12-31 00:03:17974browse

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'])

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

3. Specify the Target Column

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

df1['e'] = ...

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)

b. Method Prior to 2017

df1['e'] = e_values

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!

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