Как создать Pandas DataFrame из серии (с примерами)
Часто вы можете захотеть создать pandas DataFrame из одной или нескольких серий pandas.
В следующих примерах показано, как создать pandas DataFrame, используя существующие ряды в качестве строк или столбцов DataFrame.
Пример 1: создание Pandas DataFrame с использованием серий в качестве столбцов
Предположим, у нас есть следующие три серии панд:
Мы можем использовать следующий код для преобразования каждой серии в DataFrame, а затем объединить их все в один DataFrame:
Обратите внимание, что каждая из трех серий представлена в виде столбцов в окончательном кадре данных.
Пример 2: создание Pandas DataFrame с использованием серий в качестве строк
Предположим, у нас есть следующие три серии панд:
Мы можем использовать следующий код для объединения каждой серии в кадр данных pandas, используя каждую серию в качестве строки в кадре данных:
Обратите внимание, что каждая из трех серий представлена в виде строк в окончательном кадре данных.
Дополнительные ресурсы
В следующих руководствах объясняется, как выполнять другие распространенные операции в Python:
Convert pandas Series to DataFrame
And I would like to transform it to the following DataFrame:
I found a way to do it, but I doubt it’s the more efficient one:
![]()
7 Answers 7
Rather than create 2 temporary dfs you can just pass these as params within a dict using the DataFrame constructor:
There are lots of ways to construct a df, see the docs
to_frame():
Starting with the following Series, df:
I use to_frame to convert the series to DataFrame:
Now all you need is to rename the column name and name the index column:
Your DataFrame is ready for further analysis.
Update: I just came across this link where the answers are surprisingly similar to mine here.
![]()
One line answer would be
![]()
Series.reset_index with name argument
Often the use case comes up where a Series needs to be promoted to a DataFrame. But if the Series has no name, then reset_index will result in something like,
Where you see the column name is «0». We can fix this be specifying a name parameter.
How to create a dataframe from Pandas series ?
![]()
Sometimes we have to store selected columns from a dataframe to another dataframe for further steps during data preprocessing stage. In this article we will see how we can create a new dataframe from Pandas series.
Let’s understand how this can be done.
Importing Pandas library.
Reading the csv file.
Suppose we need to store ‘Pregnancies’ , ‘BloodPressure’ and ‘Age’ in another dataframe.
How to Convert Pandas Series to a DataFrame
In this tutorial, you’ll see how to convert Pandas Series to a DataFrame. You’ll also observe how to convert multiple Series into a DataFrame.
To begin, here is the syntax that you may use to convert your Series to a DataFrame:
Alternatively, you can use this approach to convert your Series:
In the next section, you’ll see how to apply the above syntax using a simple example.
Steps to Convert Pandas Series to DataFrame
Step 1: Create a Series
To start with a simple example, let’s create Pandas Series from a List of 5 items:
Run the code in Python, and you’ll get the following Series:
Note that the syntax of print(type(my_series)) was added at the bottom of the code in order to demonstrate that we created a Series (as highlighted in yellow above).
Step 2: Convert the Pandas Series to a DataFrame
Next, convert the Series to a DataFrame by adding df = my_series.to_frame() to the code:
Run the code, and you’ll now get a DataFrame:
In the above case, the column name is ‘0.’ Alternatively, you may rename the column by adding df = df.rename(columns = <0:’item’>) to the code:
You’ll now see the new column name at the top:
Convert Multiple Series to Pandas DataFrame
Now you’ll observe how to convert multiple Series (for the following data) into a DataFrame.