Home > Software design >  Use apply() instead of FOR loop to create dictionary from dataframe
Use apply() instead of FOR loop to create dictionary from dataframe

Time:12-22

How can I achieve the same result as in script below, but using some function and apply()? I know about list comprehensions, but it's only apply() without loops acceptable.

x_dict = {}
for indx, row in df.iterrows():
    x_dict[indx] = df

I expected to get dict with keys, which is indexes of dataframe, with using some function and apply() without any loops and comprehensions. Is it possible?

CodePudding user response:

I think this is what you are trying to do. If close, you can use these callouts to construct final product.

import pandas

df = pd.DataFrame(dict(cola=[1,2,3,4], colb=[4,5,6,7]))
df.apply(lambda row: print(f'index={row.name}, data={row.to_dict()}'), axis=1)

index=0, data={'cola': 1, 'colb': 4}
index=1, data={'cola': 2, 'colb': 5}
index=2, data={'cola': 3, 'colb': 6}
index=3, data={'cola': 4, 'colb': 7}

If you're trying to build a json struct or something, you'll have to manually construct the dict

def update(row, x_dict):
    x_dict.update({row.name: row})
 
x_dict = dict()
df.apply(lambda row: update(row, x_dict), axis=1)

#x_dict[3] output 

|      |   3 |
|:-----|----:|
| cola |   4 |
| colb |   7 |

CodePudding user response:

IIUC you are looking for:

x_dict = {}
def get_dict(x):
    x_dict[x.name] = pd.DataFrame([x.values], columns=x.index)

where x.name gives you the index in apply function and your result will be in x_dict.

OR if you want list as values in your dict.

x_dict = {}
def get_dict(x):
    x_dict[x.name] = x.values.tolist()

Then use

df.apply(get_dict, axis=1)

and

print(x_dict)
  • Related