One way to do this would be to take the column names as a separate list and then only give from 1st index for pd.DataFrame -

In [8]: data = [['Name','Rank','Complete'],
   ...:                ['one', 1, 1],
   ...:                ['two', 2, 1],
   ...:                ['three', 3, 1],
   ...:                ['four', 4, 1],
   ...:                ['five', 5, 1]]

In [10]: df = pd.DataFrame(data[1:],columns=data[0])

In [11]: df
Out[11]:
    Name  Rank  Complete
0    one     1         1
1    two     2         1
2  three     3         1
3   four     4         1
4   five     5         1

If you want to set the first column Name column as index, use the .set_index() method and send in the column to use for index. Example -

In [16]: df = pd.DataFrame(data[1:],columns=data[0]).set_index('Name')

In [17]: df
Out[17]:
       Rank  Complete
Name
one       1         1
two       2         1
three     3         1
four      4         1
five      5         1
Answer from Anand S Kumar on Stack Overflow
Top answer
1 of 3
55

One way to do this would be to take the column names as a separate list and then only give from 1st index for pd.DataFrame -

In [8]: data = [['Name','Rank','Complete'],
   ...:                ['one', 1, 1],
   ...:                ['two', 2, 1],
   ...:                ['three', 3, 1],
   ...:                ['four', 4, 1],
   ...:                ['five', 5, 1]]

In [10]: df = pd.DataFrame(data[1:],columns=data[0])

In [11]: df
Out[11]:
    Name  Rank  Complete
0    one     1         1
1    two     2         1
2  three     3         1
3   four     4         1
4   five     5         1

If you want to set the first column Name column as index, use the .set_index() method and send in the column to use for index. Example -

In [16]: df = pd.DataFrame(data[1:],columns=data[0]).set_index('Name')

In [17]: df
Out[17]:
       Rank  Complete
Name
one       1         1
two       2         1
three     3         1
four      4         1
five      5         1
2 of 3
1

To create the desired dataframe from construction, the list could be converted into a numpy array and indexed accordingly.

arr = np.array(data, dtype=object)
df = pd.DataFrame(arr[1:, 1:], index=pd.Index(arr[1:, 0], name=arr[0,0]), columns=arr[0, 1:], dtype=int)

Another method is, since the data looks like a csv file read into a Python list, it could be converted into an in-memory text buffer and have pd.read_csv called on it. A nice thing about read_csv is that it can set MultiIndex columns, indices etc. and can infer dtypes.

from io import StringIO
df = pd.read_csv(StringIO('\n'.join(['|'.join(map(str, row)) for row in data])), sep='|', index_col=[0])


A convenience function for the latter method:

from io import StringIO
def read_list(data, index_col=None, header=0):
    sio = StringIO('\n'.join(['|'.join(map(str, row)) for row in data]))
    return pd.read_csv(sio, sep='|', index_col=index_col, header=header)

df = read_list(data, index_col=[0])
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ convert nested list into a dataframe where all each list becomes a row in the dataframe (instead of separating into separate columns)
r/learnpython on Reddit: Convert nested list into a dataframe where all each list becomes a row in the dataframe (instead of separating into separate columns)
January 23, 2023 -

I have a nested list which I'd like to convert into a dataframe and add each list item to a new row. i've seen a few exams showing how to separate the list into different columns but none on how to keep the list together (separated by "" and , ) but add it to separate rows.

As an example

data = [['one', 1, 1], ['two', 2, 1], ['three', 3, 1]]

and output would be

List
['one', 1, 1]
['two', 2, 1]
['three', 3, 1]

The reason being is i have multiple lists i want to add to the same dataframe. 1 column will be the sentences of the text. the next column is the split up words but i want it to be kept with the original sentence.

Thanks

๐ŸŒ
YouTube
youtube.com โ€บ let me flutter
How to Convert Python Nested List to Dataframe Row | Python Tutorial - YouTube
In this tutorial, we'll learn how to properly convert Python nested list to Dataframe row with the help of a practical Python code example.Watch this tutoria...
Published ย  July 29, 2023
Views ย  31
๐ŸŒ
Tutorial Gateway
tutorialgateway.org โ€บ convert-python-list-to-pandas-dataframe
Convert Python List To Pandas DataFrame
April 5, 2025 - List Items = ['kiwi', 'orange', 'banana', 'berry', 'mango', 'cherry'] List Items = [100, 2000, 5000, 400, 8000, 12000] Fruits Orders a kiwi 100 b orange 2000 c banana 5000 d berry 400 e mango 8000 f cherry 12000 ยท The DataFrame function also converts the nested lists.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to create nested lists from a pandas dataframe?
r/learnpython on Reddit: How to create nested lists from a pandas dataframe?
December 28, 2021 -

I am working on creating a small job shop scheduler and need to convert my data from SQL table to nested lists in python.

Order Number process_id machine_id process_time changover_time_1 machine_id sfg_id rm_id
Order 1 1 11 720 90 11 179 37
Order 1 1 12 360 90 12 142 55
Order 1 2 13 360 90 13 46 55
Order 1 3 15 720 90 15 180 8
Order 2 1 11 240 90 11 68 8
Order 2 2 13 720 90 13 43 24
Order 2 2 14 600 90 14 175 4
Order 2 3 16 480 90 16 172 40
Order 2 3 15 480 90 15 209 40

There are two levels in this table. First is process_id where a single order can be executed on alternative machines. I need to create a list for every process stage in the order. Inside the list will be a tuple of form (machine_id, process_time, changeover_time_1, machine_id, sfg_id, rm_id).

The output will look something like this:

Order Number process_id tuple 2
Order 1 1 (11,720,90,11,179), (12,360,90,12,142)
Order 1 2 (13,360,90,13,46)
Order 1 3 (15,720,90,15,180)
Order 2 1 (11,240,90,11,68)
Order 2 2 (13,720,90,13,43), (14,600,90,14,175)
Order 2 3 (16,480,90,16,172), (15,480,90,15,209)

Now the all the processes inside the order are included as lists inside a list for every order. The output will look something like this:

Order Number tuple 3
Order 1 [(11,720,90,11,179), (12,360,90,12,142)], [(13,360,90,13,46)], [(15,720,90,15,180)]
Order 2 [(11,240,90,11,68)], [(13,720,90,13,43), (14,600,90,14,175)], [(16,480,90,16,172), (15,480,90,15,209)]

I have tried using df.values.tolist() but I can't get the nested lists. I have also tried to convert it into the dictionary and create tuples. It only works for a single stage of the process but I can't think of how to make it work for multiple stages. Previous attempt here

๐ŸŒ
Plain English
plainenglish.io โ€บ home โ€บ blog โ€บ python โ€บ converting nested list into a pandas dataframe
Converting Nested List into a Pandas DataFrame
May 31, 2021 - The following code is used to flatten the nested list โ€˜staโ€™ to a list called โ€˜all_stationsโ€™.
Find elsewhere
๐ŸŒ
Medium
vedprakash-nitjsr.medium.com โ€บ unpacking-nested-lists-with-pandas-exploring-data-using-df-explode-8990e43905da
Unpacking Nested Lists with Pandas: Exploring Data Using df.explode() | by Ved Prakash | Medium
August 24, 2023 - Each key-value pair becomes a tuple, forming a list of tuples that defines the DataFrameโ€™s structure. ... The df.explode() function is the crux of this process. It works on columns containing lists and "explodes" these lists into individual rows.
๐ŸŒ
DEV Community
dev.to โ€บ foxinfotech โ€บ convert-a-list-to-a-pandas-dataframes-a-complete-guide-for-data-manipulation-52n4
Convert a List to a Pandas DataFrame: A Complete Guide for Data Manipulation - DEV Community
May 29, 2025 - Complex data structures often require preprocessing before conversion to DataFrames. These scenarios include mixed data types, hierarchical structures, and irregular list formats commonly encountered in real-world applications. import pandas as pd import json # Converting JSON-like nested structures json_like_data = [ { 'user_id': 'U001', 'profile': {'name': 'John Doe', 'age': 30}, 'preferences': ['sports', 'technology', 'music'], 'scores': {'math': 85, 'science': 92} }, { 'user_id': 'U002', 'profile': {'name': 'Jane Smith', 'age': 28}, 'preferences': ['art', 'travel'], 'scores': {'math': 90,
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ python-convert-list-of-nested-dictionary-into-pandas-dataframe
Python - Convert list of nested dictionary into Pandas Dataframe
December 28, 2020 - import pandas as pd # Given nested dictionary list = [ { "Fruit": [{"Price": 15.2, "Quality": "A"}, {"Price": 19, "Quality": "B"}, {"Price": 17.8, "Quality": "C"}, ], "Name": "Orange" }, { "Fruit": [{"Price": 23.2, "Quality": "A"}, {"Price": 28, "Quality": "B"} ], "Name": "Grapes" } ] rows = [] # Getting rows for data in list: data_row = data['Fruit'] n = data['Name'] for row in data_row: row['Name'] = n rows.append(row) # Convert to data frame df = pd.DataFrame(rows) print(df)
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ creating-pandas-dataframe-using-list-of-lists
Creating Pandas dataframe using list of lists - GeeksforGeeks
December 9, 2025 - Below code creates a Pandas DataFrame from a list of lists, converting the 'Age' column to numeric format and handling errors, with the result printed.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 47947281 โ€บ how-to-make-nested-list-into-rows-and-columns-in-a-data-frame-in-python
pandas - How to make nested list into rows and columns in a data frame in Python - Stack Overflow
I need my list to be in the format of rows and columns shown below (I think it is called a data frame), with its contents having the Pythagorean formula applied against each cells' column and row header: ... Save this answer. ... Show activity on this post. If I understand correcty, this should solve your problem: Copyimport pandas as pd df = pd.DataFrame(coor_house) df['l2'] = np.sqrt((df[1].apply(lambda x :x[0]) -df[0].apply(lambda x :x[0]))**2 +(df[1].apply(lambda x :x[1]) -df[0].apply(lambda x :x[1]))**2)
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ build a dataframe from multiple nested lists?
r/learnpython on Reddit: Build a dataframe from multiple nested lists?
January 20, 2022 -

Hi all, I'm new to Python and have been struggling with the response from a REST API, so looking for some help from the pros.

I've created a simplified version of the json structure below but it's nested lists within lists within a list

data = { "status": 200,
         "errmsg": "OK",
         "data": { "total": 2,
                   "items": [{ "id": 1,
                               "displayname": "name1",
                               "type":        "type1",

                               "properties": [ { "name": "property1", "value": "value1" },
                                               { "name": "property2", "value": "value2" }],

                               "details":    [ { "name": "detail1", "value": "value1" },
                                               { "name": "detail2", "value": "value2" },
                                               { "name": "detail3", "value": "value3" }]},

                             { "id": 2,
                               "displayname": "name2",
                               "type":        "type2",

                               "properties": [ { "name": "property1", "value": "value1" },
                                               { "name": "property2", "value": "value2" }],

                                "details":   [ { "name": "detail1", "value": "value1" },
                                               { "name": "detail2", "value": "value1" }]
                             }]
                 }
       }

I need an output that looks like the below:

displaynametypeproperty2detail1detail3
name1type1value2value1value3
name2type2value2value1NaN

And I've made some progress with this:

import pandas as pd

properties = pd.json_normalize(data['data']['items'], record_path='properties', meta=['displayname','type'])
df = pd.DataFrame(properties)
filter = df.loc[df['name'] == 'property2']
pivot = filter.pivot(index=['displayname','type'], columns='name', values='value')

print(pivot)

Which gets me to:

displaynametypeproperty2
name1type1value2
name2type2value2

That's half the job as I've managed to get the columns from the meta level, and then the single column I want from the 'properties' list, but because I've specified the relative_path in json.normalize to be 'properties', I can't get the columns I need from 'details'.

I could duplicate my code and change the relative path to 'details' but there's an extra layer of complication here in that I want to create two columns from the values found in 'details' - detail 1 & detail 3 - but detail 3 only exists for one of the records, so I would expect a NaN there (I think)?

NOTE: In my real json response, there's 320 records, of which not all of them will have a 'property' or 'detail' that I'm looking for, but I still want all 320 records (displaynames) to appear in my dataframe.

Can anyone offer any tips or advice on how can get this across the finish line?

Thank you in advance!

Top answer
1 of 2
2
Not sure if it's of use to you - but I usually find it easier to transform the data before passing it to pandas. for i, item in enumerate(data['data']['items']): props = item.pop('properties') detail = item.pop('details') prop2 = next((p for p in props if p['name'] == 'property2'), {}) deta1 = next((d for d in detail if d['name'] == 'detail1'), {}) deta3 = next((d for d in detail if d['name'] == 'detail3'), {}) item['property2'] = prop2.get('value') item['detail1'] = deta1.get('value') item['detail3'] = deta3.get('value') data['data']['items'][i] = item Then you can create a dataframe from it: >>> pd.DataFrame(data['data']['items']) id displayname type property2 detail1 detail3 0 1 name1 type1 value2 value1 value3 1 2 name2 type2 value2 value1 None
2 of 2
2
pandas alone is not equipped to parse your JSON in exactly the way you need. For that, you'll need to create a function that traverses your JSON and extracts only the subset of fields that you need, then create a dataframe from that. For example: def parse_json(j): nan = float('nan') data = dict() for i, item in enumerate(j['data']['items']): data[i] = {'displayname' : item['displayname'], 'type' : item['type'], 'property2' : item['properties'][1]['value'], 'detail1' : item['details'][0]['value']} if len(item['details']) >= 3: data[i]['detail3'] = item['details'][2]['value'] return data In action: >>> import pandas as pd >>> j = {'status': 200, ... 'errmsg': 'OK', ... 'data': {'total': 2, ... 'items': [{'id': 1, ... 'displayname': 'name1', ... 'type': 'type1', ... 'properties': [{'name': 'property1', 'value': 'value1'}, ... {'name': 'property2', 'value': 'value2'}], ... 'details': [{'name': 'detail1', 'value': 'value1'}, ... {'name': 'detail2', 'value': 'value2'}, ... {'name': 'detail3', 'value': 'value3'}]}, ... {'id': 2, ... 'displayname': 'name2', ... 'type': 'type2', ... 'properties': [{'name': 'property1', 'value': 'value1'}, ... {'name': 'property2', 'value': 'value2'}], ... 'details': [{'name': 'detail1', 'value': 'value1'}, ... {'name': 'detail2', 'value': 'value1'}]}]}} >>> df = pd.DataFrame(parse_json(j)).T >>> df displayname type property2 detail1 detail3 0 name1 type1 value2 value1 value3 1 name2 type2 value2 value1 NaN
Top answer
1 of 1
1

Is it what you're trying to achieve?

Try it online!

import pandas as pd
from pandas import Timestamp

l = [
 [[1, Timestamp('2019-01-22 00:54:27')]],
 [[2, Timestamp('2019-01-22 08:37:04')]],
 [[3, Timestamp('2019-01-22 10:57:40')],
  [4, Timestamp('2019-01-22 10:57:43')]],
 [[5, Timestamp('2019-01-22 11:09:07')],
  [6, Timestamp('2019-01-22 11:16:18')],
  [7, Timestamp('2019-01-22 11:16:23')],
  [8, Timestamp('2019-01-22 11:16:25')]],
 [[9, Timestamp('2019-01-22 11:35:03')],
  [10, Timestamp('2019-01-22 11:35:35')]],
]

df = pd.DataFrame(
    [e1 + [g] for g, e0 in enumerate(l) for e1 in e0],
    columns = ['id', 'time', 'group'],
)

print('As one DataFrame:\n', df)

dfs = [
    pd.DataFrame(
        [e1 + [g] for e1 in e0],
        columns = ['id', 'time', 'group'],
    )
    for g, e0 in enumerate(l)
]

print('\nAs separate DataFrames:')

for df in dfs:
    print('---------------------')
    print(df)

Outputs

As one DataFrame:
    id                time  group
0   1 2019-01-22 00:54:27      0
1   2 2019-01-22 08:37:04      1
2   3 2019-01-22 10:57:40      2
3   4 2019-01-22 10:57:43      2
4   5 2019-01-22 11:09:07      3
5   6 2019-01-22 11:16:18      3
6   7 2019-01-22 11:16:23      3
7   8 2019-01-22 11:16:25      3
8   9 2019-01-22 11:35:03      4
9  10 2019-01-22 11:35:35      4

As separate DataFrames:
---------------------
   id                time  group
0   1 2019-01-22 00:54:27      0
---------------------
   id                time  group
0   2 2019-01-22 08:37:04      1
---------------------
   id                time  group
0   3 2019-01-22 10:57:40      2
1   4 2019-01-22 10:57:43      2
---------------------
   id                time  group
0   5 2019-01-22 11:09:07      3
1   6 2019-01-22 11:16:18      3
2   7 2019-01-22 11:16:23      3
3   8 2019-01-22 11:16:25      3
---------------------
   id                time  group
0   9 2019-01-22 11:35:03      4
1  10 2019-01-22 11:35:35      4
Top answer
1 of 2
1

I think the simple will remain for loops.

  1. First, select all keys from the given features.

    1. For all elements, we use str.split and extract the first element.
    2. Then, because we only want unique keys, we use set. Then, we convert it back to list and sort the keys using sorted (here some details if needed).

The first is sum up in:

keys = sorted(list(set([elt.split(':')[0] for l in features for elt in l])))
  1. Create an empty dict from the above keys and initialize all keys with an empty list:
data = {k:[] for k in keys}
  1. Iterate over all the features:

    1. Save all the key features visited in a seen variable
    2. Add all featured keys and values
    3. Complete the data with keys not in the current features
  2. Eventually, create the dataframe from out dict using the default constructor [pd.DataFrame()] (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html).

  3. Correctly format columns name using .columns and string formatting (format). Here are some good explanations.


Talked enough, here the full code + illustration:

features = [["0:0.084556", "1:0.138594", "2:0.094304"],
    ["0:0.101468", "4:0.138594", "5:0.377215"],
    ["0:0.135290", "2:0.277187", "3:0.141456"]
    ]

# Step 1
keys = sorted(list(set([elt.split(':')[0] for l in features for elt in l])))
print(keys)
# ['0', '1', '2', '3', '4', '5']

# Step 2
data = {k:[] for k in keys}
print(data)
# {'0': [], '1': [], '2': [], '3': [], '4': [], '5': []}

# Step 3
for sub in features:
    # Step 3.1
    seen = []
    # Step 3.2
    for l in sub:
        k2, v = l.split(":")        # Get key and value
        data[k2].append(float(v))   # Append current value to data
        seen.append(k2)             # Set the key as seen

    # Step 3.3
    for k in keys:                  # For all data keys
        if k not in seen:           # If not seen
            data[k].append(0)       # Add 0

print(data)
# {'0': [0.084556, 0.101468, 0.13529], 
#     '1': [0.138594, 0, 0], 
#     '2': [0.094304, 0,0.277187],
#     '3': [0, 0, 0.141456],
#     '4': [0, 0.138594, 0],
#     '5': [0, 0.377215, 0]
# }

# Step 4
df = pd.DataFrame(data)
print(df)
#           0         1         2         3         4         5
# 0  0.084556  0.138594  0.094304  0.000000  0.000000  0.000000
# 1  0.101468  0.000000  0.000000  0.000000  0.138594  0.377215
# 2  0.135290  0.000000  0.277187  0.141456  0.000000  0.000000

# Step 5
df.columns = ["f_{:04d}".format(int(val)) for val in df.columns]
print(df)
#      f_0000    f_0001    f_0002    f_0003    f_0004    f_0005
# 0  0.084556  0.138594  0.094304  0.000000  0.000000  0.000000
# 1  0.101468  0.000000  0.000000  0.000000  0.138594  0.377215
# 2  0.135290  0.000000  0.277187  0.141456  0.000000  0.000000
2 of 2
-2

try this:

df = pd.DataFrame(data, columns = ['Column name 1'], ['column name 2'])
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-convert-list-of-nested-dictionary-into-pandas-dataframe
Python | Convert list of nested dictionary into Pandas dataframe - GeeksforGeeks
July 11, 2025 - In this step, a new list named "rows" is initialized to store flattened data. The code iterates through the original list of dictionaries, extracting each student's exam details along with their name and appends the flattened rows to create a Pandas DataFrame, which is then displayed.