Pandas How to Convert Series to DataFrame Easily
series.to_frame() or by passing the Series to pd.DataFrame() constructor like pd.DataFrame(series).Examples
How to Think About It
to_frame() method, which keeps the Series name as the column name, or by creating a new DataFrame from the Series directly. This way, the Series values become the DataFrame column values.Algorithm
Code
import pandas as pd # Create a Series s = pd.Series([10, 20, 30], name='numbers') # Convert Series to DataFrame using to_frame() df1 = s.to_frame() print(df1) # Convert Series to DataFrame using pd.DataFrame() df2 = pd.DataFrame(s) print(df2)
Dry Run
Let's trace converting Series s = pd.Series([10, 20, 30], name='numbers') to DataFrame using to_frame()
Create Series
s = pd.Series([10, 20, 30], name='numbers')
Call to_frame()
s.to_frame() creates DataFrame with column 'numbers' and rows 10, 20, 30
Return DataFrame
DataFrame with one column 'numbers' and index 0,1,2
| Index | numbers |
|---|---|
| 0 | 10 |
| 1 | 20 |
| 2 | 30 |
Why This Works
Step 1: Series as single column
A pandas Series is like a single column of data with an index. Converting it to a DataFrame means wrapping it as a table with one column.
Step 2: Using to_frame() method
The to_frame() method converts the Series into a DataFrame keeping the Series name as the column name.
Step 3: Using DataFrame constructor
Passing the Series to pd.DataFrame() creates a DataFrame with the Series values as a column and the Series name as the column header.
Alternative Approaches
import pandas as pd s = pd.Series([1, 2, 3], name='A') df = s.reset_index() df.columns = ['index', 'A'] print(df)
import pandas as pd s = pd.Series([4, 5, 6], name='B') df = pd.DataFrame.from_dict({s.name: s}) print(df)
Complexity: O(n) time, O(n) space
Time Complexity
Converting a Series to DataFrame requires copying or referencing all n elements, so it takes O(n) time.
Space Complexity
The new DataFrame stores the same data plus metadata, so it uses O(n) space proportional to the Series length.
Which Approach is Fastest?
to_frame() and pd.DataFrame(series) have similar performance; alternatives like reset_index add overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| series.to_frame() | O(n) | O(n) | Simple conversion preserving column name |
| pd.DataFrame(series) | O(n) | O(n) | Direct constructor use, flexible |
| reset_index() | O(n) | O(n) | When index needs to be a column |
| pd.DataFrame.from_dict() | O(n) | O(n) | When working with dicts or multiple series |
series.to_frame() for a quick and clean conversion preserving the Series name as column header.