Home > OS >  Inserting values from a dictionary in a pandas Dataframe
Inserting values from a dictionary in a pandas Dataframe

Time:08-11

I am new to data science and python. I am having trouble trying to fill values in columns of a table.

There is a table with rows device_id, age, gender, group other columns.

I also have a dictionary consisting of device_id values as keys and a list of gender, age and group values {device_id: [gender, age, group]}

I am trying to iterate through the table and check the device_id of each row against the key value in the dictionary. On match, I intend to to assign the values in the relevant columns.

However I am not able to do that. Can someone show the way ahead??

Thanks

CodePudding user response:

Simplest way

Use don't have to iterate to dictionary, you can directly do like below

import pandas as pd
df = pd.DataFrame()

dict = {
    #deviceid : [gender, age, group]
    "device_1" : ["m", 25, "group_1"],
    "device_2" : ["f", 22, "group_2"],
    "device_3" : ["f", 20, "group_2"],
    "device_4" : ["m", 80, "group_6"]
}

df = pd.DataFrame(dict)
print(df)

#Output
#  device_1 device_2 device_3 device_4
#0        m        f        f        m
#1       25       22       20       80
#2  group_1  group_2  group_2  group_6

CodePudding user response:

Sample

m = sample_df['Col1'].isin(sample_list)
sample_df[m].groupby('Col1')['Col2'].apply(list).to_dict()

Returns: {101: ['NJ', 'NJ', 'NJ'], 105: ['CA', 'CA'], 112: ['NB']}

  • Related