Home > Mobile >  Pandas - appending dictionary to existing row
Pandas - appending dictionary to existing row

Time:10-15

For each row, I am computing values and storing them in a dictionary. I want to be able to take the dictionary and add it to the row where the keys are columns.

For example:

Dataframe

A  B  C
1  2  3

Dictionary:

{
    'D': 4,
    'E': 5
}

Result:

A  B  C  D  E
1  2  3  4  5

There will be more than one row in the dataframe, and for each row I'm computing a dictionary that might not necessarily have the same exact keys.

CodePudding user response:

I ended up doing this to get it to work:

appiled_df = df.apply(lambda row: func(row['a']), axis='columns', result_type='expand')
df = pd.concat([df, appiled_df], axis='columns')

def func():
    ...
    return pd.Series(dictionary)

CodePudding user response:

You can try:

d = {
    'D': 4,
    'E': 5
}


df.join(pd.Series(d).to_frame().T)

Result:

   A  B  C  D  E
0  1  2  3  4  5
  • Related