0

我有以下按 user_id 和 action 列分组的记录。

user_id | action | count
1       | read   | 15
1       | write  | 5
1       | delete | 7
2       | write  | 2
3       | read   | 9
3       | write  | 1
3       | delete | 2

我想将此表转换为以下格式,其中每个操作现在是一列,行是计数值。

user_id | read | write | delete
1       | 15   | 5     | 7
2       | 0    | 2     | 0
3       | 9    | 1     | 2

我知道如何使用循环来做到这一点,但我很好奇在 GraphLab 创建 SFrame 或 Panda 的 DataFrame 中是否有更有效的方法。

我很感激任何帮助!

4

2 回答 2

3

你可以pivot

df.pivot_table('count', 'user_id', 'action', fill_value=0)

在此处输入图像描述

于 2017-01-08T15:27:00.270 回答
1

您可以使用pivotwithfillna和 last cast floatto intby astype

df = df.pivot(index='ser_id', columns='action', values='count').fillna(0).astype(int)
print (df)
action  delete  read  write
ser_id                     
1            7    15      5
2            0     0      2
3            2     9      1

另一个解决方案set_indexand unstack

df = df.set_index(['ser_id','action'])['count'].unstack(fill_value=0)
print (df)
action  delete  read  write
ser_id                     
1            7    15      5
2            0     0      2
3            2     9      1

如果列中的重复项ser_idand actionand pivotorunstack不能使用,解决方案是groupby聚合meanorsum和 reshape by unstack

df = df.groupby(['ser_id','action'])['count'].mean().unstack(fill_value=0)
print (df)
action  delete  read  write
ser_id                     
1            7    15      5
2            0     0      2
3            2     9      1

时间:

#random dataframe
np.random.seed(100)
N = 10000
df = pd.DataFrame(np.random.randint(100, size=(N,3)), columns=['user_id','action', 'count'])
#[10000000 rows x 2 columns]
print (df)

In [124]: %timeit (df.groupby(['user_id','action'])['count'].mean().unstack(fill_value=0))
100 loops, best of 3: 5.5 ms per loop

In [125]: %timeit (df.pivot_table('count', 'user_id', 'action', fill_value=0))
10 loops, best of 3: 35.9 ms per loop
于 2017-01-08T15:27:27.617 回答