Combining two Series into a DataFrame in Pandas

PandasServer Side ProgrammingProgramming

To combine two series into a DataFrame in Pandas, we can take two series and concatenate them using concat() method.

Steps

  • Create series 1 with two elements, where index is ['a', 'b'] and name is Series 1.

  • Print Series 1.

  • Make Series 2 with two elements, where index is ['a', 'b'] and name is Series 2.

  • Print Series 2.

  • Concatenate Pandas objects along a particular axis with optional set logic along the other axes.

  • Print the resultant DataFrame.

Example

 Live Demo

import pandas as pd

s1 = pd.Series([4, 16], index=['a', 'b'], name='Series 1')
print "Input series 1 is: \n", s1

s2 = pd.Series([3, 9], index=['a', 'b'], name='Series 2')
print "Input series 2 is: \n", s2

df = pd.concat([s1, s2], axis=1)
print "Resultant DataFrame is:\n", df

Output

Input series 1 is:
a   4
b   16
Name: Series 1, dtype: int64
Input series 2 is:
a   3
b   9
Name: Series 2, dtype: int64

Resultant DataFrame is:
    Series 1 Series 2
a     4       3
b    16       9
raja
Published on 30-Aug-2021 12:22:38
Advertisements