我正在从api中流一些有关SaaS小部件用户的数据,并希望根据“用户活动”进行一些分析,以找到这个过程中的效率。我希望能回答一些问题,比如“用户行为的哪些(组)导致成功完成”等等。
目前,数据是一个有时间戳的响应日志,包括特定用户的分类功能,以及特定交互期间的具体操作和响应:
Timestamp User Cat1 Cat2 Action Response
timenow User1 False barbar action1 response4
time(n-1) User2 False No value action1 response3
time(n-2) User1 False barbar baraction response2
time(n-3) User3 True bar action1 response1
time(n-4) User2 False foo action1 response2
time(n-5) User1 False barbar fooaction response1我想按用户对数据进行分组,然后列出所有包含计数的操作:
User Cat1 Cat2 Action1 Action2 Response1 Response 2
User3 True bar 2 1 7 1
User2 False foo 4 5 8 4
User1 False barbar 5 2 3 0 我可以想象这样做的熊猫,使用循环创建一个新的数据框架的格式,我所追求的。然而,我想知道在熊猫中是否有这样做的好方法,或者是否有更好的形式(群?)哪一种可能会产生类似的结果?
发布于 2016-06-20 12:23:10
我不完全理解你的输出。时间戳列在哪里?如何选择Cat1和Cat2值?
至于其余的,您可以使用get_dummies和groupby
创建输入数据文件:
import io
temp = u"""Timestamp User Cat1 Cat2 Action Response
timenow User1 False barbar action1 response4
time(n-1) User2 False Novalue action1 response3
time(n-2) User1 False barbar baraction response2
time(n-3) User3 True bar action1 response1
time(n-4) User2 False foo action1 response2
time(n-5) User1 False barbar fooaction response1"""
df = pd.read_csv(io.StringIO(temp),delim_whitespace = True)输出:
Timestamp User Cat1 Cat2 Action Response
0 timenow User1 False barbar action1 response4
1 time(n-1) User2 False Novalue action1 response3
2 time(n-2) User1 False barbar baraction response2
3 time(n-3) User3 True bar action1 response1
4 time(n-4) User2 False foo action1 response2
5 time(n-5) User1 False barbar fooaction response1使用get_dummies,您可以得到所需的列:
df = df[['User','Action','Response']]
df = pd.concat([df,df['Action'].str.get_dummies(),df['Response'].str.get_dummies()],axis = 1)
df.drop(['Action','Response'],1,inplace = True)
User action1 baraction fooaction response1 response2 response3 response4
0 User1 1 0 0 0 0 0 1
1 User2 1 0 0 0 0 1 0
2 User1 0 1 0 0 1 0 0
3 User3 1 0 0 1 0 0 0
4 User2 1 0 0 0 1 0 0
5 User1 0 0 1 1 0 0 0最后使用groupby
df.groupby('User',as_index = False).sum()
User action1 baraction fooaction response1 response2 response3 response4
0 User1 1 1 1 1 1 0 1
1 User2 2 0 0 0 1 1 0
2 User3 1 0 0 1 0 0 0https://stackoverflow.com/questions/37919725
复制相似问题