Table of Contents
Creating a Pandas DataFrame from a Series is quite simple. You can create a DataFrame from a single Series, or multiple Series. To do this, you can simply pass the Series into the DataFrame constructor, and specify the columns you want the Series to be in. You can also add additional columns to the DataFrame by using the assign() method. With these methods, you can easily create a DataFrame from a single or multiple Series.
Often you may want to create a pandas DataFrame from one or more pandas Series.
The following examples show how to create a pandas DataFrame using existing series as either the rows or columns of the DataFrame.
Example 1: Create Pandas DataFrame Using Series as Columns
Suppose we have the following three pandas Series:
import pandas as pd #define three Series name = pd.Series(['A', 'B', 'C', 'D', 'E']) points = pd.Series([34, 20, 21, 57, 68]) assists = pd.Series([8, 12, 14, 9, 11])
We can use the following code to convert each series into a DataFrame and then concatenate them all into one DataFrame:
#convert each Series to a DataFrame
name_df = name.to_frame(name='name')
points_df = points.to_frame(name='points')
assists_df = assists.to_frame(name='assists')
#concatenate three Series into one DataFrame
df = pd.concat([name_df, points_df, assists_df], axis=1)
#view final DataFrame
print(df)
name points assists
0 A 34 8
1 B 20 12
2 C 21 14
3 D 57 9
4 E 68 11
Notice that the three series are each represented as columns in the final DataFrame.
Example 2: Create Pandas DataFrame Using Series as Rows
Suppose we have the following three pandas Series:
import pandas as pd #define three Series row1 = pd.Series(['A', 34, 8]) row2 = pd.Series(['B', 20, 12]) row3 = pd.Series(['C', 21, 14])
We can use the following code to combine each of the Series into a pandas DataFrame, using each Series as a row in the DataFrame:
#create DataFrame using Series as rows
df = pd.DataFrame([row1, row2, row3])
#create column names for DataFrame
df.columns = ['col1', 'col2', 'col3']
#view resulting DataFrame
print(df)
col1 col2 col3
0 A 34 8
1 B 20 12
2 C 21 14
Notice that the three series are each represented as rows in the final DataFrame.
The following tutorials explain how to perform other common operations in Python: