简体   繁体   中英

Expand column values from a grouped-by DataFrame into proper columns

After a GroupBy operation I have the following DataFrame:

数据框

The user_id is grouped with their respective aisle_id as I want. Now, I want to turn the aisle_id values into columns, having the user_id as a index, and all the aisle_id as columns. Then, in the values I want to have the amount of times the user_id and aisle_id have matched in the previous DataSet. For example, if the user_id 1 has bought from the aisle_id 12 in 3 occasions, the value in DF[1,12] would be 3.

With Pandas pivot tables I can get the template of the user_id as index, and the aisle_id as columns, but I can't seem to find the way to create the values specified above.

considering your first dataframe is df, I think you could try this :

df2=pd.DataFrame(index=df['user_id'].unique(),columns=df['aisle_id'].unique())
for i in df2.index :
  for j in df2.columns :
    df2.at[i,j]=len(df.loc[(df['user_id']==i) & (df['aisle_id']==j)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM