Python DataFrame列转键值对咨询:能否达成预期输出?
Hey there! Let's figure out how to transform your DataFrame into the key-value format you need. Since I can’t view the images you mentioned, I’ll cover the two most common scenarios for this kind of conversion—you can tweak these examples to match your actual data structure and desired output.
Scenario 1: Each Row as a Key-Value Dictionary (List of Dictionaries)
If you want every row in your DataFrame to become an individual key-value pair dictionary (where column names are keys and row values are the corresponding values), use the to_dict('records') method:
import pandas as pd # Example DataFrame (replace with your actual data) df = pd.DataFrame({ 'ID': [101, 102, 103], 'Product': ['Laptop', 'Phone', 'Tablet'], 'Price': [999, 699, 299] }) # Convert to list of key-value dictionaries key_value_output = df.to_dict('records') print(key_value_output)
Output:
[{'ID': 101, 'Product': 'Laptop', 'Price': 999}, {'ID': 102, 'Product': 'Phone', 'Price': 699}, {'ID': 103, 'Product': 'Tablet', 'Price': 299}]
Scenario 2: Single Key-Value Dictionary (One Column as Keys, Another as Values)
If you need a single dictionary where one column’s values are the keys and another column’s values are the corresponding values, use set_index() combined with to_dict():
# Convert 'Product' column to keys and 'Price' column to values key_value_dict = df.set_index('Product')['Price'].to_dict() print(key_value_dict)
Output:
{'Laptop': 999, 'Phone': 699, 'Tablet': 299}
If your desired format is different (like nested key-value pairs, or a specific custom structure), just describe what you’re aiming for—happy to adjust the solution!
内容的提问来源于stack exchange,提问作者Tarek Khedr

