R
R
Rustem2016-04-04 00:36:42
Python
Rustem, 2016-04-04 00:36:42

How to cast a DataFrame to a dictionary/dataframe of the right kind using Pandas?

There is a select query.

print("Connecting to database...") 
db = psycopg2.connect(host='localhost', user='postgres', password = 'password', database = 'DB') 
print("Connected!") 
print("Processing...") 
prefs = pd.read_sql("select distinct ord.user_id, line.variant_id, count(line.order_id) " + 
"from spree_line_items line " + 
"join spree_orders ord on(line.order_id=ord.id) " + 
"where ord.state='shipped' and ord.user_id is not null " + 
"group by line.variant_id, ord.user_id " + 
"order by ord.user_id;" 
, con=db)
prefs.columns=['user', 'var', 'mark']
print("Adding marks...") 
prefs.loc[prefs.mark>1, 'mark']=5
prefs.loc[prefs.mark==1, 'mark']=4

Ratings are given if the user has ordered product variant 1 or more times with ratings 4 and 5, respectively.
When outputting the resulting dataframe, I get the following picture:
16fc1b72eaa943d2bafc6d260034f9c0.PNG
Attention, question! How to make a dictionary of the form from a given dataframe: df_dict={user1:{var_id1 : mark1, var_id2 : mark2...},..., usern: {var_id : mark,....}} or arrange a dataframe where user is 1st row, and var is the indexing column, then mark is the cell of the user matrix on var.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2016-04-04
@sim3x

pandas.pydata.org/pandas-docs/stable/generated/pan...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question