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

Python 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 Python skills with w3resource's quiz



Python: Tips of the Day

Merging two dicts in Python 3.5+ with a single expression

Example:

# How to merge two dictionaries
# in Python 3.5+

x = {'p': 1, 'q': 3}
y = {'q': 5, 'r': 8}

z = {**x, **y}

z
{'r': 4, 'p': 1, 'q': 3}

z = dict(x, **y)
print(z)

Output:

{'p': 1, 'q': 5, 'r': 8}