Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Convert a List to a DataFrame Row in Python?
Python's pandas library provides powerful tools for data manipulation. Converting a list to a DataFrame row is a common task when you need to add new data to existing datasets. This tutorial shows you how to convert a list into a DataFrame row using pandas.
Method 1: Using pd.DataFrame() Constructor
The most straightforward approach is to create a DataFrame directly from a list with specified column names:
import pandas as pd # Create a list of data new_row_data = ['Prince', 26, 'New Delhi'] # Convert list to DataFrame row df = pd.DataFrame([new_row_data], columns=['Name', 'Age', 'City']) print(df)
Name Age City
0 Prince 26 New Delhi
Method 2: Using pd.Series with to_frame()
You can create a Series first and then convert it to a DataFrame:
import pandas as pd # Create a list of data data = ['Alice', 30, 'Mumbai'] columns = ['Name', 'Age', 'City'] # Convert to Series then DataFrame series = pd.Series(data, index=columns) df = series.to_frame().T # Transpose to make it a row print(df)
Name Age City
0 Alice 30 Mumbai
Method 3: Adding to Existing DataFrame
To add a list as a new row to an existing DataFrame, use pd.concat():
import pandas as pd
# Existing DataFrame
existing_df = pd.DataFrame({
'Name': ['John', 'Sarah'],
'Age': [25, 35],
'City': ['Delhi', 'Kolkata']
})
# New row data
new_row = ['Mike', 28, 'Chennai']
# Create new row DataFrame
new_row_df = pd.DataFrame([new_row], columns=existing_df.columns)
# Add to existing DataFrame
result_df = pd.concat([existing_df, new_row_df], ignore_index=True)
print(result_df)
Name Age City
0 John 25 Delhi
1 Sarah 35 Kolkata
2 Mike 28 Chennai
Using Dictionary for Better Readability
For better code readability, you can use a dictionary instead of a plain list:
import pandas as pd
# Using dictionary for clarity
row_dict = {'Name': 'Emma', 'Age': 32, 'City': 'Bangalore'}
# Convert dictionary to DataFrame row
df = pd.DataFrame([row_dict])
print(df)
Name Age City
0 Emma 32 Bangalore
Comparison
| Method | Best For | Pros | Cons |
|---|---|---|---|
| DataFrame Constructor | Simple conversion | Direct, fast | Need to specify columns |
| Series + to_frame() | Complex operations | More control | Extra step required |
| pd.concat() | Adding to existing data | Handles indices well | More complex syntax |
| Dictionary approach | Clear data mapping | Very readable | More typing required |
Conclusion
Converting a list to a DataFrame row is simple using pandas. Use the DataFrame constructor for direct conversion, pd.concat() for adding to existing data, and dictionary approach for better readability. Choose the method that best fits your specific use case.
