You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas中将字典转为DataFrame?并直接访问字典内的DataFrame?

How to Access DataFrames Stored in a Dictionary & Handle Conversion Issues in Pandas

Hey there! Let's break this down and get you sorted out. First, let's confirm I understand your setup correctly: you've got a dictionary where each key (top and rising) maps to its own full Pandas DataFrame, right? Here's a quick example of what that might look like:

import pandas as pd

# Example child DataFrames
top_df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]})
rising_df = pd.DataFrame({'colA': [7, 8, 9], 'colB': [10, 11, 12]})

# Your dictionary structure
df_dict = {'top': top_df, 'rising': rising_df}

1. Directly Access the Child DataFrames

The simplest solution here is that you don't need to convert the entire dictionary to a DataFrame to access these datasets—you can grab them directly from the dictionary using their keys:

# Bracket notation (works for any key name, even with spaces/special chars)
print(df_dict['top'])

# Dot notation (only works if keys are valid Python identifiers—no spaces or symbols)
print(df_dict.rising)

This lets you access each individual DataFrame instantly, no extra conversion steps required.


2. Why Standard Dictionary-to-DataFrame Methods Failed

When you tried pd.DataFrame(df_dict) and it didn't work, that's because Pandas expects dictionary values to be 1-dimensional data (lists, arrays, etc.) for basic column-based conversion. Since your values are full DataFrames, this method just creates a DataFrame where each cell contains an entire DataFrame object—not the tabular data you're looking for.


3. If You Want to Combine the Two DataFrames into One

If your goal is to merge these two DataFrames into a single dataset instead of accessing them separately, use pd.concat():

Option A: Stack vertically (row-wise)

Works best if both DataFrames share the same column names (missing columns will fill with NaN):

combined_df = pd.concat(df_dict.values(), axis=0, ignore_index=True)

Add a source column to track which original DataFrame each row came from:

df_dict['top']['source'] = 'top'
df_dict['rising']['source'] = 'rising'
combined_df = pd.concat(df_dict.values(), axis=0, ignore_index=True)

Option B: Join horizontally (column-wise)

Works best if both DataFrames have the same number of rows (missing rows will fill with NaN):

combined_df = pd.concat(df_dict.values(), axis=1)

Hope this clears things up! Let me know if you need further adjustments based on your specific DataFrame structures.

内容的提问来源于stack exchange,提问作者yssefunc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:33:09