How to get the dictionary's certain key value pair from the column that is dictionary…
- User
How to get the dictionary's certain key value pair from the column that is dictionary object from the df
- Assistant
To get a specific key-value pair from a column that contains dictionary objects in a pandas DataFrame, you can use the
applyfunction along with a lambda function.Here's an example:
import pandas as pd # Create a sample DataFrame data = {'name': ['John', 'Jane', 'Sam'], 'details': [{'age': 25, 'city': 'New York'}, {'age': 30, 'city': 'London'}, {'age': 35, 'city': 'Paris'}]} df = pd.DataFrame(data) # Define the key you want to extract key = 'age' # Use apply and a lambda function to extract the key-value pair df['age_value'] = df['details'].apply(lambda x: x.get(key)) print(df)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.