当试图合并两个数据帧时,内存不足。所以我决定寻找一种方法,我可以做单独的计算,然后附加的结果。我遇到了这个answer
然而,我并不完全理解如何在它的结构中应用我自己的功能。下面给出了我要做的事情的细节。你知道吗
我试图从消费者购买历史记录中计算每日logit值,以了解在给定所有优惠的情况下,消费者进行购买的可能性。原始表如下所示
a_id b_received brand_id c_consumed type_received date
0 sam soap bill oil edibles 2011-01-01
1 sam oil chris NaN utility 2011-01-02
2 sam brush dan soap grocery 2011-01-03
3 harry oil sam shoes clothing 2011-01-04
4 harry shoes bill oil edibles 2011-01-05
5 alice beer sam eggs breakfast 2011-01-06
6 alice brush chris brush cleaning 2011-01-07
7 alice eggs NaN NaN edibles 2011-01-08
我的最终目标是得到这样一个只有90行(90天)的表
date logit_value
0 2011-01-01 0.42
1 2011-01-02 0.34
2 2011-01-03 0.24
3 2011-01-04 0.13
4 2011-01-05 0.49
5 2011-01-06 0.54
6 2011-01-07 0.66
7 2011-01-08 0.71
我现在迷失在如何使用我在这个批处理函数中用于较小数据集的函数来创建所需的最终数据集。你知道吗
下面给出了我用于较小数据集的代码,并解释了它的作用。你知道吗
为了计算logit,我首先需要计算输出值(0,1),确定用户是否收到了产品。我使用下面的代码得到一个输出。你知道吗
df['output'] = (df.groupby('a_id')
.apply(lambda x : x['b_received'].isin(x['c_consumed']).astype('i4'))
.reset_index(level='a_id', drop=True))
新桌子是这样的
a_id b_received brand_id c_consumed type_received date output
0 sam soap bill oil edibles 2011-01-01 1
1 sam oil chris NaN utility 2011-01-02 1
2 sam brush dan soap grocery 2011-01-03 0
3 harry oil sam shoes clothing 2011-01-04 1
4 harry shoes bill oil edibles 2011-01-05 1
5 alice beer sam eggs breakfast 2011-01-06 0
6 alice brush chris brush cleaning 2011-01-07 1
7 alice eggs NaN NaN edibles 2011-01-08 1
这里1表示产品是由特定用户使用的,0表示不是
在此之后,我需要按日期分组,并在输出列上应用一个函数,并将其存储在新的数据帧中。在这里,每天计算输出值的总和,然后除以长度,然后用于创建logit值。代码如下所示。我打算用这个代码
final_df = pd.DataFrame()
def logit(x):
prob = sum(x) / len(x)
logit = np.log(prob / (1 - prob))
return logit
final_df['daily_logit'] = (
sample_dataframe.groupby(['send_time'])['output']
.apply(logit)
.reset_index(level='user_id', drop=True))
应该给我这样的东西
date logit_value
0 2011-01-01 0.42
1 2011-01-02 0.34
2 2011-01-03 0.24
3 2011-01-04 0.13
4 2011-01-05 0.49
5 2011-01-06 0.54
6 2011-01-07 0.66
7 2011-01-08 0.71
但所有这些都取决于能否像我前面提到的那样将操作分成小批量。你知道吗
下面是另一个stackoverflow用户的代码示例,我正在尝试使用它,但到目前为止还没有成功。此代码的链接是here.
# Create input tables
t1 = {'scenario':[0,0,1,1],
'letter':['a','b']*2,
'number1':[10,50,20,30]}
t2 = {'letter':['a','a','b','b'],
'number2':[2,5,4,7]}
table1 = pd.DataFrame(t1)
table2 = pd.DataFrame(t2)
table3 = pd.DataFrame()
grouped = table1.groupby('scenario')
for _, group in grouped:
temp = pd.merge(group, table2, on='letter')
temp['calc'] = temp['number1'] * temp['number2']
table3 = table3.append(temp.loc[temp.groupby('letter')['calc'].idxmax()])
del temp
我知道这是一个很长的问题,但我已经被困在这里很长时间了。感谢您的帮助。如果我在这个问题上没有说清楚的话,请尽管问。你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐