如何从含字典的pandas DataFrame中提取带索引的'name'列
Hey there! Let's break down how to pull the 'name' column from your nutrients_df DataFrame into a new DataFrame while preserving the original index—super straightforward once you know the tricks.
Method 1: Directly Extract as DataFrame (Simplest)
Use double square brackets to select the column. This tells pandas you want a DataFrame (not a Series) right away, and it automatically keeps the original index:
name_df = nutrients_df[['name']]
Method 2: Convert Series to DataFrame
If you first extract the column as a Series (with single brackets), you can convert it to a DataFrame using the to_frame() method—this also retains the original index:
# First get the Series name_series = nutrients_df['name'] # Convert to DataFrame name_df = name_series.to_frame()
Example to See It in Action
Let's use sample data to verify:
import pandas as pd # Sample DataFrame matching your scenario data = { 'name': ['Vitamin A', 'Vitamin C', 'Calcium', 'Iron'], 'daily_value': [90, 100, 125, 11], 'unit': ['µg', 'mg', 'mg', 'mg'] } nutrients_df = pd.DataFrame(data, index=['nut1', 'nut2', 'nut3', 'nut4']) # Using Method 1 name_df = nutrients_df[['name']] print(name_df)
Output:
name nut1 Vitamin A nut2 Vitamin C nut3 Calcium nut4 Iron
You can see the original index (nut1, nut2, etc.) is fully preserved in the new name_df DataFrame.
Key Notes
- Double brackets
[['name']]are crucial here—single brackets['name']would return a pandas Series instead of a DataFrame. - Both methods maintain the original index because they're derived directly from the source DataFrame, so no index resetting happens unless you explicitly call
reset_index().
内容的提问来源于stack exchange,提问作者Alberto Alvarez

