簡體   English   中英

將 DataFrame 重塑為 RNN Keras-tensorflow 的 3D 數組?

[英]Reshape DataFrame into 3D array for RNN Keras-tensorflow?

問題

我在 Dataframe 中有每個客戶流失前 31 天的交易數據(有些客戶少於 31 天)
如何將其重塑為 3D 陣列並用 0 填充 Keras RNN?
確保它與目標的其他 Dataframe 匹配

數據結構

這個玩具樣品可以使用

df = pd.DataFrame({
        'Customer_id' : [112]*27 + [223]*31 + [256]*30
        ,'DATE' : np.concatenate([np.concatenate([np.arange(20200701,20200728) , np.arange(20200501,20200532)]), np.arange(20200501,20200531)])
        ,'Last_date_before_churn' :[20200727]*27 + [20200531]*31 + [20200530]*30
        ,'Feature1':np.random.uniform(0.1,0.9,88)
        ,'Feature2':np.random.uniform(0.1,0.9,88)
    })

# edit to replicate actual data
df = df.drop(15,axis = 0)


target = pd.DataFrame({
    'Customer_id' : [256,112,223]
    ,'IS_Churn':[1,0,1]
})

我們有 3 個客戶 [112,223,256]。 112 有 27 天沒有流失,223 有 31 天沒有流失。
當前形狀是 (88, 4) 但我們需要重塑為 (3,31,2) -> 3 個客戶,31 個時間步長和 2 個特征。 所以第三個維度是每個與目標數據框對齊的 Customer_id

另一個困難的部分是

每個客戶都有不同的日期范圍。 而我們可以看到“Last_date_before_churn”是 31 天范圍內的最后一個日期。
例如,客戶 112 的最后日期是 7 月 27 日,我們可能有從 7 月 1 日到 7 月 15 日以及從 7 月 17 日到 7 月 27 日的唯一日期的數據。 所以我們應該將日期從 6 月 27 日填充到 6 月 30 日,然后是 7 月 16 日,這樣它就變成了 31 天

我試過的

我嘗試使用 for 循環,但我的 27,928,258 行數據集的實際數據一直占用

result = []
for index, Cid in enumerate(df.Customer_id.unique()):
    result.append(df[df['Customer_id'] == Cid].iloc[:, :])

我不知道我的解決方案是否有效。 無論如何,我都會使用 go。

import pandas as pd
import numpy as np


df = pd.DataFrame({
        'Customer_id' : [112]*27 + [223]*31 + [256]*30
        ,'DATE' : np.concatenate([np.concatenate([np.arange(20200701,20200728) , np.arange(20200501,20200532)]), np.arange(20200501,20200531)])
        ,'Feature1':np.random.uniform(0.1,0.9,88)
        ,'Feature2':np.random.uniform(0.1,0.9,88)
    })
    
# Getting unique customer ids.
Series_customer_ids = df['Customer_id'].unique()

# Final array having the result.
final = np.zeros((Series_customer_ids.shape[0], 31, 2))

# Used for indexing first dimension of `final`
i = 0

for customer_id in Series_customer_ids:
    # `n_days` is the number of days for each customer. Assumed <=31.
    n_days = df[df['Customer_id']==customer_id].shape[0]
    if n_days > 0:
        np.place(
            # Location in `final` array.
            final[i],
            # Mask
            [(True, True) for _ in range(31)],
            # Pad for 31 - `n_days`.
            np.pad(
                df[df['Customer_id']==customer_id][['Feature1', 'Feature2']].to_numpy(),
                ((0, 31 - n_days), (0,0)),
                'constant'
            )
        )
    i += 1

# `final` contains the answer.

print(final.shape)
# (customer id count, days of month, features per observation)
# (3, 31, 2)

由於 memory 的限制,它可能再次失敗,或者將永遠完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM