python - Pandas dataframe to JSON format manipulation -
i have pandas dataframe one
user category rating 1 [1,2,3] [5,1,3] 2 [3,2,1] [3,1,1] 3 [1,3,1] [2,1,4]
i want write endpoint takes user , returns list of categories , ratings particular user.
www.endpoint.com/user/1
should return
[{category: 1, rating: 5}, {category: 2, rating: 1}, {category: 3, rating: 3}]
is there simple way in pandas?
i use the following generic function explodes lists in columns rows:
def explode(df, lst_cols, fill_value=''): # make sure `lst_cols` list if lst_cols , not isinstance(lst_cols, list): lst_cols = [lst_cols] # columns except `lst_cols` idx_cols = df.columns.difference(lst_cols) # calculate lengths of lists lens = df[lst_cols[0]].str.len() if (lens > 0).all(): # lists in cells aren't empty return pd.dataframe({ col:np.repeat(df[col].values, df[lst_cols[0]].str.len()) col in idx_cols }).assign(**{col:np.concatenate(df[col].values) col in lst_cols}) \ .loc[:, df.columns] else: # @ least 1 list in cells empty return pd.dataframe({ col:np.repeat(df[col].values, df[lst_cols[0]].str.len()) col in idx_cols }).assign(**{col:np.concatenate(df[col].values) col in lst_cols}) \ .append(df.loc[lens==0, idx_cols]).fillna(fill_value) \ .loc[:, df.columns]
demo:
in [88]: df out[88]: user category rating 0 1 [1, 2, 3] [5, 1, 3] 1 2 [3, 2, 1] [3, 1, 1] 2 3 [1, 3, 1] [2, 1, 4] in [89]: cols = ['category','rating'] in [90]: x = explode(df, cols) in [91]: x out[91]: user category rating 0 1 1 5 1 1 2 1 2 1 3 3 3 2 3 3 4 2 2 1 5 2 1 1 6 3 1 2 7 3 3 1 8 3 1 4
now can need:
in [92]: x.loc[x.user == 1, cols].to_dict('r') out[92]: [{'category': '1', 'rating': '5'}, {'category': '2', 'rating': '1'}, {'category': '3', 'rating': '3'}]
Comments
Post a Comment