w3resource

Pandas Data Series: Stack two given series vertically and horizontally

 


37. Stack Series

Write a Pandas program to stack two given series vertically and horizontally.

Sample Solution :

Python Code :

import pandas as pd
series1 = pd.Series(range(10))
series2 = pd.Series(list('pqrstuvwxy'))
print("Original Series:")
print(series1)
print(series2)
series1.append(series2)
df = pd.concat([series1, series2], axis=1)
print("\nStack two given series vertically and horizontally:")
print(df)

Sample Output:

Original Series:
0    0
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9
dtype: int64
0    p
1    q
2    r
3    s
4    t
5    u
6    v
7    w
8    x
9    y
dtype: object

Stack two given series vertically and horizontally:
   0  1
0  0  p
1  1  q
2  2  r
3  3  s
4  4  t
5  5  u
6  6  v
7  7  w
8  8  x
9  9  y

Explanation:

series1 = pd.Series(range(10)): This code creates a Pandas Series object called ‘series1’ containing integers from 0 to 9, generated using the range() function.

series2 = pd.Series(list('pqrstuvwxy')): This code creates another Pandas Series object called ‘series2‘ containing characters from the string "pqrstuvwxy", generated using the list() function.

series1.append(series2): This code appends ‘series2’ to ‘series1’ and returns a new Series object that includes both Series objects.

df = pd.concat([series1, series2], axis=1): This code concatenates ‘series1’ and ‘series2’ horizontally using pd.concat() and stores the result in a DataFrame called df.

Finally print() function prints the DataFrame ‘df’.


For more Practice: Solve these Related Problems:

  • Write a Pandas program to stack two Series vertically and then compute the row-wise sum.
  • Write a Pandas program to stack two Series horizontally and then calculate the element-wise product.
  • Write a Pandas program to stack two Series vertically, reset the index, and then merge with an additional Series.
  • Write a Pandas program to stack two Series horizontally and then convert the result into a MultiIndex DataFrame.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to convert given series into a dataframe with its index as another column on the dataframe.
Next: Write a Pandas program to check the equality of two given series.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.