Python - Concat series onto dataframe with column name

Learn, how to concat a series onto DataFrame with column name?
Submitted by Pranit Sharma, on August 22, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

A Series in pandas contains a single list that can store heterogeneous types of data, because of this, a series is also considered a 1-dimensional data structure.

When we analyze a series, each value can be considered as a separate row of a single column, both series and DataFrame can be created either with the list or with the help of a dictionary, in the case of series, there will be only one key in the dictionary but there may be multiple keys in case of DataFrame.

Concat series onto dataframe with column name

To concat a series onto DataFrame with a column name, we will first create a series with multiple values and then we will rename this series with some specific name and concat this series to the DataFrame so that it will act as a new column for the DataFrame.

Let us understand with the help of an example,

Python program to concat series onto dataframe with column name

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'Category':['Vehicles','Clothes','Electronics'],
    'Product':['Car','Shirt','TV'],
    'Model':['XUV 700','Peter England Slim Fit', 'Sony 8k']
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display Original DataFrame
print("Created DataFrame:\n",df,"\n")

# Creating a series
s = pd.Series([1800000,3000,30000])

# Concatenating the series
df = pd.concat((df,s.rename('Price')),axis=1)

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output

Example: Concat series onto dataframe with column name

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.