w3resource

Pandas Data Series: Convert given series into a dataframe with its index as another column on the dataframe

 

Pandas: Data Series Exercise-36 with Solution

Write a Pandas program to convert given series into a dataframe with its index as another column on the dataframe.

Sample Solution :

Python Code :

import numpy as np
import pandas as pd
char_list = list('ABCDEFGHIJKLMNOP')
num_arra = np.arange(8)
num_dict = dict(zip(char_list, num_arra))
num_ser = pd.Series(num_dict)
df = num_ser.to_frame().reset_index()
print(df.head())

Sample Output:

  index  0
0     A  0
1     B  1
2     C  2
3     D  3
4     E  4

Explanation:

char_list = list('ABCDEFGHIJKLMNOP'): This code creates a list of characters called char_list. It contains the 16 uppercase letters from A to P. Each character in the list is a string of length 1. The list() function is used to convert the string of characters into a list of individual characters.

num_arra = np.arange(8): This code creates a NumPy array 'num_arra' containing the integers from 0 to 7 using the np.arange() function.

num_dict = dict(zip(char_list, num_arra)): This code creates a dictionary 'num_dict' using the dict() function and the zip() function.

num_ser = pd.Series(num_dict): This code creates a Pandas Series 'num_ser' using the pd.Series() function and the dictionary 'num_dict' created in the previous line of code.

df = num_ser.to_frame().reset_index(): This code converts the Pandas Series 'num_ser' to a Pandas DataFrame using the to_frame() method, which returns a DataFrame with the Series values as a single column and the Series index as the index of the 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 create a TimeSeries to display all the Sundays of given year.
Next: Write a Pandas program to stack two given series vertically and horizontally.

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.