简体   繁体   English

将按分组的 DataFrame 中的列值扩展为适当的列

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

After a GroupBy operation I have the following DataFrame:在 GroupBy 操作之后,我有以下 DataFrame:

数据框

The user_id is grouped with their respective aisle_id as I want. user_id 根据我的需要与其各自的 aisle_id 分组。 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.现在,我想将 aisle_id 值转换为列,将 user_id 作为索引,并将所有 aisle_id 作为列。 Then, in the values I want to have the amount of times the user_id and aisle_id have matched in the previous DataSet.然后,在值中,我希望 user_id 和 aisle_id 在前一个数据集中匹配的次数。 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.例如,如果 user_id 1 在 3 次从 aisle_id 12 购买,则 DF[1,12] 中的值为 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.使用 Pandas 数据透视表,我可以将 user_id 的模板作为索引,将 aisle_id 作为列,但我似乎无法找到创建上面指定的值的方法。

considering your first dataframe is df, I think you could try this :考虑到你的第一个数据帧是 df,我想你可以试试这个:

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)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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