如何将嵌套列表字典转换为指定结构的pandas DataFrame?
Why Your Current Code Isn't Working
When you use pd.DataFrame.from_dict(dict1, orient='index'), pandas treats the dictionary key (808) as the index and the nested list as separate columns. This results in a single row where each column holds an inner list—definitely not the flattened structure you're aiming for. Let's fix that with two straightforward approaches.
Method 1: Manual Row Construction (Intuitive for Beginners)
We'll loop through the dictionary to build a list of complete rows, where each row starts with the memberid followed by the elements from each sublist. Then we convert this list to a DataFrame with your desired column names.
import pandas as pd dict1 = {808: [['a', 5.4, 'b'], ['c', 4.1, 'b'], ['d', 3.7, 'f']]} # Build a list of full rows rows = [] for memberid, entries in dict1.items(): for entry in entries: rows.append([memberid] + entry) # Create the DataFrame with specified columns df = pd.DataFrame(rows, columns=['memberid', 'userid', 'score', 'related']) print(df)
Output:
memberid userid score related 0 808 a 5.4 b 1 808 c 4.1 b 2 808 d 3.7 f
Method 2: Pandas-Native Approach (Using Explode)
If you prefer a more pandas-focused workflow, you can use explode() to expand the nested list into separate rows, then split the exploded column into individual columns.
import pandas as pd dict1 = {808: [['a', 5.4, 'b'], ['c', 4.1, 'b'], ['d', 3.7, 'f']]} # Convert dict to initial DataFrame and rename columns df = pd.DataFrame.from_dict(dict1, orient='index').reset_index() df.columns = ['memberid', 'data'] # Explode the list into individual rows df = df.explode('data') # Split the 'data' column into separate columns df[['userid', 'score', 'related']] = pd.DataFrame(df['data'].tolist(), index=df.index) # Drop the temporary 'data' column df = df.drop('data', axis=1) print(df)
This will produce the exact same output as Method 1.
内容的提问来源于stack exchange,提问作者Wendy D.

