我有一个像这样的数组:
year week app_id period
0 2015 22 [g8m4lecv, uyhsx6lo, u9ue1zzo, kw06m3f5, wvqhq... 2015-22
1 2015 23 [608a223c57e1174fc64775dd2fd8cda387cc4a47, ze4... 2015-23
2 2015 24 [kz8udlea, zwqo7j8w, 6d02c9d74b662369dc6c53ccc... 2015-24
3 2015 25 [fgs0qhtf, awkcmpns, e0iraf3a, oht91x5j, mv4uo... 2015-25
4 2015 26 [zwqo7j8w, dzdfiof5, phwoy1ea, e7hfx7mu, 40fdd... 2015-26
唯一ID的DataFrame:
unique_app_ids
0 g8m4lecv
1 uyhsx6lo
2 u9ue1zzo
3 kw06m3f5
4 wvqhq7d7
5 fucjx9ar
6 ede963a7c7b854938c1196bb83dc3a0924951055
7 ze4rr0vi
我想要做的是,对于unique_app_ids中的每个app_id:
然后,我想在weekly usage
的唯一ID列中添加一列。
这是我到目前为止所处的位置:
startperiod = True;
stopped = True;
usage = 0
weeklyadoption= adopters['app_id'].values;
def retention_rate(row):
for app_id in retention['unique_app_ids']:
for week in range(len(weeklyadoption)):
if weeklyadoption[week].isin(app_id):
stopped = False;
usage+=1
else:
stopped = True;
return usage
retention['weekly_retention']=retention.apply(retention_rate, axis=1)
其中retention
是唯一ID的数据框,adopters
是数组数组。但是,我没有测试代码,因为我无法思考:
修改
即使是当前的代码也没有循环。我明白了:
AttributeError: ("'numpy.ndarray' object has no attribute 'isin'", u'occurred at index 0')
请注意,weeklyadoption
在打印时看起来像这样:
[([array],[array]....)]
答案 0 :(得分:0)
您要做的事情有几个问题:
你的循环中有一个return
语句,这就是它退出循环的原因。
目前还不清楚为什么将2d数据存储在数组中,1d存储在DataFrame中。相反的情况对我来说更有意义。
以下是基于这些建议实施的解决方案:
weekly_usage = {}
df['app_id_str'] = df['app_id'].apply(lambda x: ('|').join(x))
for app_id in unique_app_ids:
temp = df[df['app_id_str'].str.contains(app_id)].sort('period')
# at this point, if it's continuous, you can just take the length
# start, end = temp['period'].min(), temp['period'].max()
duration = len(temp) #or you can use timedelta if you want a time difference
weekly_usage[app_id] = duration
有了这个,你就会有一个unique_ids字典及其持续时间,你可以随意显示它们。