
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Combine Two Series and Convert to DataFrame in Python
Assume, you have two series and the result for combining two series into dataframe as,
Id Age 0 1 12 1 2 13 2 3 12 3 4 14 4 5 15
To solve this, we can have three different approaches.
Solution 1
Define two series as series1 and series2
Assign first series into dataframe. Store it as df
df = pd.DataFrame(series1)
Create a column df[‘Age’] in dataframe and assign second series inside to df.
df['Age'] = pd.DataFrame(series2)
Example
Let’s check the following code to get a better understanding −
import pandas as pd series1 = pd.Series([1,2,3,4,5],name='Id') series2 = pd.Series([12,13,12,14,15],name='Age') df = pd.DataFrame(series1) df['Age'] = pd.DataFrame(series2) print(df)
Output
Id Age 0 1 12 1 2 13 2 3 12 3 4 14 4 5 15
Solution 2
Define a two series
Apply pandas concat function inside two series and set axis as 1. It is defined below,
pd.concat([series1,series2],axis=1)
Example
Let’s check the following code to get a better understanding −
import pandas as pd series1 = pd.Series([1,2,3,4,5],name='Id') series2 = pd.Series([12,13,12,14,15],name='Age') df = pd.concat([series1,series2],axis=1) print(df)
Output
Id Age 0 1 12 1 2 13 2 3 12 3 4 14 4 5 15
Solution 3
Define a two series
Assign first series into dataframe. Store it as df
df = pd.DataFrame(series1)
Apply pandas join function inside series2. It is defined below,
df = df.join(series2) pd.concat([series1,series2],axis=1)
Example
Let’s check the following code to get a better understanding −
import pandas as pd series1 = pd.Series([1,2,3,4,5],name='Id') series2 = pd.Series([12,13,12,14,15],name='Age') df = pd.DataFrame(series1) df = df.join(series2) print(df)
Output
Id Age 0 1 12 1 2 13 2 3 12 3 4 14 4 5 15
Advertisements